我知道这是一个非常基本的问题.我很困惑为什么以及如何以下不同.
char str[] = "Test";
char *str = "Test";
Run Code Online (Sandbox Code Playgroud)
K-b*_*llo 26
char str[] = "Test";
Run Code Online (Sandbox Code Playgroud)
是一个数组chars
,用"Test"中的内容初始化,同时
char *str = "Test";
Run Code Online (Sandbox Code Playgroud)
是指向文字(const)字符串"Test"的指针.
它们之间的主要区别在于第一个是数组而另一个是指针.该数组拥有其内容,它恰好是副本"Test"
,而指针只是引用字符串的内容(在这种情况下是不可变的).
指针可以重新指向其他东西:
char foo[] = "foo";
char bar[] = "bar";
char *str = foo; // str points to 'f'
str = bar; // Now str points to 'b'
++str; // Now str points to 'a'
Run Code Online (Sandbox Code Playgroud)
递增指针的最后一个示例表明,您可以轻松地迭代字符串的内容,一次一个元素.
一个是指针,一个是数组.它们是不同类型的数据.
int main ()
{
char str1[] = "Test";
char *str2 = "Test";
cout << "sizeof array " << sizeof(str1) << endl;
cout << "sizeof pointer " << sizeof(str2) << endl;
}
Run Code Online (Sandbox Code Playgroud)
产量
sizeof array 5
sizeof pointer 4
Run Code Online (Sandbox Code Playgroud)
不同之处在于使用的STACK内存.
例如,当为微控制器编程时,为堆栈分配的内存非常少,会产生很大的不同.
char a[] = "string"; // the compiler puts {'s','t','r','i','n','g', 0} onto STACK
char *a = "string"; // the compiler puts just the pointer onto STACK
// and {'s','t','r','i','n','g',0} in static memory area.
Run Code Online (Sandbox Code Playgroud)
首先
char str[] = "Test";
Run Code Online (Sandbox Code Playgroud)
是一个由五个字符组成的数组,用值"Test"
加上null终止符初始化'\0'
.
第二
char *str = "Test";
Run Code Online (Sandbox Code Playgroud)
是指向文字字符串的内存位置的指针"Test"
.
从 C++11 开始,第二个表达式现在无效,必须编写为:
\n\nconst char *str = "Test";\n
Run Code Online (Sandbox Code Playgroud)\n\n该标准的相关章节是附录C第1.1节:
\n\n\n\n更改:字符串文字变为 const
\n\n字符串文字的类型从 char\xe2\x80\x9d 的 \xe2\x80\x9carray 更改为 const char 的 \xe2\x80\x9carray\n。\xe2\x80\x9d char16_t 字符串文字的类型为从\n \xe2\x80\x9carray of some-integer-type\xe2\x80\x9d 更改为 \xe2\x80\x9carray of const char16_t。\xe2\x80\x9d char32_t 字符串文字的类型从\xe2\x80\x9carray of some-integer-type\xe2\x80\x9d\n 到 \xe2\x80\x9carray of const char32_t。\xe2\x80\x9d 宽字符串文字的类型从 \n 更改为 \n wchar_t\xe2\x80\x9d 的 xe2\x80\x9carray 到 const wchar_t.\xe2\x80\x9d 的 \xe2\x80\x9carray
\n\n基本原理:这可以避免调用不适当的重载函数,\n 函数可能期望能够修改其参数。
\n\n对原始特征的影响:更改明确定义的特征的语义。
\n