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

南楼画角 提交于 2019-12-04 13:50:06

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

pizza

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.

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!