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

后端 未结 5 1349
醉梦人生
醉梦人生 2021-01-16 01:11

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

相关标签:
5条回答
  • 2021-01-16 01:25

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

    0 讨论(0)
  • 2021-01-16 01:32

    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.

    0 讨论(0)
  • 2021-01-16 01:32

    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" };
    
    0 讨论(0)
  • 2021-01-16 01:32

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

    You can declare your string as follows:

    char * myString = "String";
    
    0 讨论(0)
  • 2021-01-16 01:38

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

    0 讨论(0)
提交回复
热议问题