Strings and Arrays in C language

Viewed 87
#include <stdio.h>
int main() 
{ 
    printf("%d", "123456"[1]);
    return 0;
}

The expected output is 123456, but it actually outputs 50. Why is that?

3 Answers

"123456"[1] gives the character '2'. That character's ascii value is 50.

To print the full number do: printf ("%d", 123456); or printf ("%s", "123456");

You are trying to print an integer using %d but you have provided a char instead. To get your expected output, either you have to provide an integer as 2nd argument to printf or use %s as format specifier.

printf ("%d", 123456); or printf ("%s", "123456");

Now, explanation about the output 50 you are getting:

Here, "123456" is a const char *, so when you tried to fetch value from a particular index using [1], it takes the index 1 of your const char * which is char 2.

index -> 0 1 2 3 4 5

input -> 1 2 3 4 5 6

Now, as you were printing using format specifier %d (integer), it printed the ASCII value of char 2, which is 50.

If you need the exact string then there's no need of format specifiers you can simply do

printf("123456");

You are getting output as 50 because in C String are considered as array of char and it can typecast values according to format specifiers too.

So here "123456" becomes an array. char at 1 index is 2. and integer value of char "2" i.e ascii value of 2 is 50. Hence the output.

Related