char[] char* string 的关系

来源:互联网 发布:ehviewer老是网络错误 编辑:程序博客网 时间:2024/06/04 19:47
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"></span>char a[6] = "12345";</span><span style="font-family: Arial, Helvetica, sans-serif;"></span>//该内存在栈中分配,可以改变a的值 如 a[0] = 'a'
char *str = a;<span style="white-space:pre"></span>// str指针指向 a<span style="white-space:pre"></span>std::string str1 = "hello";<span style="white-space:pre"></span>str1[0] = 'k';<span style="white-space:pre"></span>//这里是可以使用的<span style="white-space:pre"></span>char* b = "const value";<span style="white-space:pre"></span>//const 变量。在常量区分配,其中b指针在栈中,不可以改变值 如b[0] = 'a1';会崩溃strcpy_s(a, str1.c_str());
<span style="white-space:pre"></span>//printf("%s\n",str1.c_str());<span style="white-space:pre"></span>//使用c字符输出<span style="white-space:pre"></span>//std::cout << str1;<span style="white-space:pre"></span>//这里使用流输出字符串
<pre name="code" class="cpp"><span style="white-space:pre"></span>//从结果可以知道,str指针 和a指针都在在栈中,指向了同一个地址"123456",“123456”也在栈中分配<span></span>
printf("a:%d str:%d str1:%d\n", &a, &str, &str1);
printf("a:%d str:%d str1:%d\n", a, str, str1);
结果:
a:3536824 str:3536812 str1:3536776a:3536824 str:3536824 str1:8624496请按任意键继续. . .请按任意键继续. . .
0 0
原创粉丝点击