【发布时间】:2011-08-16 17:13:22
【问题描述】:
可能重复:
Difference between using character pointers and character arrays
两者有什么区别:
const char* myVar = "Hello World!";
const char myVar[] = "Hello World!";
如果有的话?
【问题讨论】:
可能重复:
Difference between using character pointers and character arrays
两者有什么区别:
const char* myVar = "Hello World!";
const char myVar[] = "Hello World!";
如果有的话?
【问题讨论】:
指针可以重新赋值,数组不能。
const char* ptr = "Hello World!";
const char arr[] = "Hello World!";
ptr = "Goodbye"; // okay
arr = "Goodbye"; // illegal
另外,正如其他人所说:
sizeof(ptr) == size of a pointer, usually 4 or 8
sizeof(arr) == number of characters + 1 for null terminator
【讨论】:
首先是一个指针。
其次是一个数组。
系统中所有指针的大小将相同。
第二个声明中的数组大小等于字符串文字加上\0的大小。
您可以将第一个指针指向任何其他相同类型的变量。
您不能重新分配数组。
【讨论】:
第一个是指针:sizeof(myVar) == sizeof(void*)。它是非常量的,所以你可以修改它:myVar++。
第二个是一个数组:sizeof(myVar) == 13。
【讨论】: