Eric.Q
Eric.Q

Reputation: 733

Difference of sizeof between char* x and char x[]

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?

Upvotes: 4

Views: 7711

Answers (4)

jiw
jiw

Reputation: 1

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++

Upvotes: 0

pizza
pizza

Reputation: 7630

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.

Upvotes: 10

chrisaycock
chrisaycock

Reputation: 37930

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().

Upvotes: 4

Pubby
Pubby

Reputation: 53037

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*).

Upvotes: 3

Related Questions