tags:

views:

178

answers:

5

Why is 49, 50, 51, 52 stored in the array when I declare testArray[] = {'1','2','3','4','5'}? How should i initialize a string array? Thanks

+17  A: 

You are initialising the array with characters, and what is stored in the array are the ASCII values of those characters.

You can print the character values using something like this:

for (int i = 0; i < sizeof(testArray)/sizeof(testArray[0]); i++) {
    printf("character '%c', ASCII value %d\n", testArray[i], testArray[i]);
}

The first value printed with %c interprets the number as the ASCII value of the character to print. The same value printed with %d prints the number itself.

Greg Hewgill
+1: you're fast.
LB
+4  A: 

Because those are the ASCII codes for the number characters. To have a string array you have to do something like this:

char *testArray[] = { "1", "2", "3", "4", "5" };
Lukáš Lalinský
+1  A: 

because 49, 50, 51 are the ASCII codes for 1,2,3... You're initializing an array of characters, not strings

Simon_Weaver
+1  A: 

Because chars are actually stored as their corresponding value in ASCII.

You can declare your string as follows:

char * myString = "String";
Maximilian Mayerl
`const char * myString = "String";` please :)
pmg
+2  A: 

If you wanted an array of numeric values, it should have been initialized as {1,2,3,4,5}. Putting the numerals in single quotes means they are characters, and the 49, 50, 51,... you are seeing are the ASCII codes for the characters '1', '2', '3', '4'.

FrustratedWithFormsDesigner