Printf () prints the entire array

Suppose I have the following code in my C program:

#include <stdio.h> void PrintSomeMessage( char *p ); int main(int argc, char *argv[]) { char arr[10] = "hello"; PrintSomeMessage(&arr[0]); return 0; } void PrintSomeMessage(char *p) { printf("p: %s",p); } 

Why would the output of this be the whole word β€œhello” instead of a single β€œh” character?

I understand, however, that if I put "%c" in the formatter, it will only print one letter. But still, the memory address for each letter in this address is different. Please, will someone explain this to me?

+8
c arrays char printf
source share
2 answers

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

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

+24
source share

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

Consider a number of houses (each of them is an element of the array). To determine the string, you only need the first address of the house. You know that each house is followed by the following (sequential). Having received the address of the 1st house, you will also indicate the address of the line.

Inclusion of string literals (character arrays defined during declaration), they are automatically added \0 .

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

+4
source share

All Articles