开发者

Why is 49, 50, 51, 52 stored in the array when I declare testArray[] = {'1','2','3','4','5'}? (C programming)

Why is 49, 50, 51, 52 stored in the array wh开发者_开发百科en I declare testArray[] = {'1','2','3','4','5'}? How should i initialize a string array? Thanks


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.


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" };


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'.


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


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

You can declare your string as follows:

char * myString = "String";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜