4

I know some difference between char* and char[]. char x[] = "xxxx" Is an array of chars; char *y = "xxxx" is a pointer to the literal (const) string; And x[4]=='\0', and *(y+4) == '\0' too. So why sizeof(x)==5 and sizeof(y)==4?

Eric.Q
  • 703
  • 1
  • 9
  • 21
  • 2
    define x as char x[] = "xxxxxxxx" instead. THen ask yourself the same question...Hint: terminating '\0' – Mitch Wheat May 12 '12 at 02:22
  • 1
    @MitchWheat I think he understands that x has five characters. The issue is that y is a pointer so sizeof(y) = 4 (bytes). – mgiuffrida May 12 '12 at 02:40
  • @eli: yes, I know that. But I didn't want to give a direct answer. Teach a man to fish and all that.... – Mitch Wheat May 12 '12 at 02:45
  • @MitchWheat the terminating '\0' has nothing to do with his question though. He knows about the terminating '\0', he's using that to show that there are five characters so the size should be 5. If you had said define y as char *y = "xxxxxxxx" instead, then he would've seen the size stayed constant. – mgiuffrida May 12 '12 at 02:50
  • possible duplicate of [C: differences between pointer and array](http://stackoverflow.com/questions/1335786/c-differences-between-pointer-and-array) and many others... – Jens Gustedt May 12 '12 at 06:55
  • Yes, I get to know x and y are both terminating '\0',and strlen(x)==strlen(y)==4, but I made a mistake sizeof(char*) will be always be 4... – Eric.Q May 14 '12 at 12:38
  • Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com/). – Keith Thompson Jun 03 '13 at 00:43

4 Answers4

10

char x[] = "xxxx" is an array of size 5 containing x x x x and \0.

char *y = "xxxx" is a pointer to a string. It's length is 4 bytes, because that is the length of the pointer, not the string.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
pizza
  • 7,296
  • 1
  • 25
  • 22
4

The sizeof an array type is the size the array takes up. Same as sizeof("xxxx").

The sizeof a pointer type is the size the pointer itself takes up. Same as sizeof(char*).

Pubby
  • 51,882
  • 13
  • 139
  • 180
4

x is really "xxxx\0". The nul terminator at the end of the string gives the array five bytes.

However, sizeof(y) is asking for the size of a pointer, which happens to be four bytes in your case. What y is pointing to is of no consequence to the sizeof().

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
0

For char *x, x is a pointer, which means you can change the pointed-to position by x++, x+=2, etc. char x[] is an array, which is a constant pointer so you cannot do x++

jiw
  • 1
  • 1