What is the difference between char array vs char

2018-12-31 12:36发布

I am trying to understand pointers in C but I am currently confused with the following:

  • char *p = "hello"
    

    This is a char pointer pointing at the character array, starting at h.

  • char p[] = "hello"
    

    This is an array that stores hello.

What is the difference when I pass both these variables into this function?

void printSomething(char *p)
{
    printf("p: %s",p);
}

7条回答
步步皆殇っ
2楼-- · 2018-12-31 13:31

For cases like this, the effect is the same: You end up passing the address of the first character in a string of characters.

The declarations are obviously not the same though.

The following sets aside memory for a string and also a character pointer, and then initializes the pointer to point to the first character in the string.

char *p = "hello";

While the following sets aside memory just for the string. So it can actually use less memory.

char p[10] = "hello";
查看更多
登录 后发表回答