开发者

const char myVar* vs. const char myVar[] [duplicate]

开发者 https://www.devze.com 2023-03-28 06:45 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Difference between using character pointers and charac开发者_如何学运维ter arrays
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Difference between using character pointers and charac开发者_如何学运维ter arrays

What's the difference between:

const char* myVar = "Hello World!";
const char  myVar[] = "Hello World!";

If there is one?


The pointer can be reassigned, the array cannot.

const char* ptr = "Hello World!";
const char  arr[] = "Hello World!";

ptr = "Goodbye"; // okay
arr = "Goodbye"; // illegal

Also, as others have said:

sizeof(ptr) == size of a pointer, usually 4 or 8
sizeof(arr) == number of characters + 1 for null terminator


First is a pointer.
Second is an array.

Size of all pointers in an system will be the same.
Size of the array in second declaration is same as the size of the string literal plus the \0.

You can point the first pointer to any other variable of the same type.
You cannot reassign the array.


The first is a pointer: sizeof(myVar) == sizeof(void*). It is non-constant, so you can modify it: myVar++.

The second is an array: sizeof(myVar) == 13.

0

精彩评论

暂无评论...
验证码 换一张
取 消