简体   繁体   中英

Unexpected output when printing element of array in c

I am creating a simple c program and output of below program should be 2 but i am getting 50 dont know why (i am newbie to c) please let me know where i am missing

#include<stdio.h>
int main(int argc, char** argv) {
   int a[4]={'1','2','2','\0'};
   printf("The value of a is %d",a[1]);
   return 0;
}

here is live output

You initialised the array using ascii character codes . '2' has integer value 50.

Initialise the array as

int a[4]={1,2,2,0};

if you want it to contain integers 1,2,2,0. Or

#include<stdio.h>
int main(int argc, char** argv) {
   char a[4]="121";
   printf("The value of a is %c",a[1]);
   return 0;
}

if you want an array of characters that can be treated as a string. (Note the use of the %c format specifier here.)

50 is the ASCII code of '2' .

Replace '2' with 2 if you want it fixed.

When using character literals like '2' C actually thinks of them as integer types. When you print it using %d format specifier you're telling C to print the value as integer.

If you want to keep the array elements like this: '2' , you'll need to change printf format to %c to get a 2 in the console.

When you wrote int a[4]={'1','2','2','\\0'}; you actually initialized the array with ASCII Codes of the numbers 1 and 2. This is because you enclosed them within single quotes thus making them characters instead of integers. Hence the array actually takes the values int a[4]={49,50,50,0};
To rectify it, you should write the integers without the quotes:

int a[4]={1,2,2,0};

Also note that integer arrays don't need to end with '\\0' . That is only for character arrays.

This line

int a[4]={'1','2','2','\0'};

tells the compiler to create an integer array of length 4 and put into it the integers from the curled braces from the right.

Characters in C are 1-byte integers, 1 is a character of 1 and it means integer value of it's ASCII code, ie 50. So the first element of an array gets the value of 50.

To fix you should write

int a[4]={1,2,2,0};

remember, that 0 cannot serve as an array end marker, since it is just a number.

If you suppose to get 122 output then do

char a[4]={'1','2','2','\0'};
printf("The value of a is %s",a);

since strings in C are character arrays with 0 as termination symbol.

Also you can let compiler to count values for you

char a[]={'1','2','2','\0'};

You are assigning chars not integers:

note

'2' means char       use %c
 2  manes int        use %d
"2" means string.    use %s

all are different:

in your code you can do like to print 2:

int main(int argc, char** argv) {
   char a[4]={'1','2','2','\0'};
   printf("The value of a is %c",a[1]);
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM