Guys, any idea why this code doesnt work?Code:int main() { int lastDigit; char num1[3] = "123"; lastDigit = strlen(num1) - 1; printf("%c", num1[lastDigit]); return 0; }
I want to get the last character of the string. In that case its "3"
Guys, any idea why this code doesnt work?Code:int main() { int lastDigit; char num1[3] = "123"; lastDigit = strlen(num1) - 1; printf("%c", num1[lastDigit]); return 0; }
I want to get the last character of the string. In that case its "3"
Last edited by Salem; 11-06-2020 at 03:03 AM. Reason: Removed eye-bleed colour scheme
Because
char num1[3] = "123";
does NOT have a \0 at the end of it for strlen() to do it's thing properly.
Write
char num1[4] = "123";
or better, let the compiler do the work
char num1[] = "123";
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.