printf() prints whole array

前端 未结 2 1837
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 01:27

Let\'s assume I have the following code in my C program:

#include 

void PrintSomeMessage( char *p );

int main(int argc, char *         


        
相关标签:
2条回答
  • 2021-02-08 02:02

    But still, the memory address for each letter in this address is different.

    Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

    0 讨论(0)
  • 2021-02-08 02:19

    Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

    Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

    Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

    printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

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