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

后端 未结 5 1361
醉梦人生
醉梦人生 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: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.

提交回复
热议问题