NullPointerException NullPointerException - 3 months ago 28
C Question

printf() prints whole array

Let's assume 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 the output of this would be the whole word "hello" instead of a single character "h"?

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

Answer

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

Comments