C++ 中数组的初始化分配内存的大小

来源:百度知道 编辑:UC知道 时间:2024/06/07 17:44:45
/*结构的调用*/
#include<iostream>
#include <cstring>
#include<string>
using namespace std;

void put(string s);

int main()
{
char c[4] = {'T','a','o'};
char t[] = {'T','a','o'};
char t2[] = {'T','a','o','z','h','i'};
char apply[] = {' ',' ',' ',' '};
cout << strlen(c) << endl;
cout << strlen(t) << endl;
cout << strlen(t2) << endl;
cout << strlen(apply) << endl;
strcpy (apply,c);
cout << apply << endl;
return 0;
}

3
7
15
19
Tao
Press any key to continue
怎么会这样?

其实你这个程序的运行结果不是唯一的,在不同的编译器上,结果都可能不相同!
问题就出在你所有的字符串数组最后没给结束符'\0',strlen()这个函数计算字符串长度时,是根据'\0'来判断字符串结束的.
所以你没给'\0',就使得出来的结果完全依赖于内存的分配了(比如,strlen(c),从c的地址开始,几时有了一个值为0x00--也就是'\0'--的地址,就结束计算长度,返回结果,这个结果就不知道是个啥了,呵呵)

改正:
把数组定义改为:
char c[4] = {'T','a','o','\0'}; //定义了4个元素,也应该给全嘛!
char t[] = {'T','a','o','\0'};
char t2[] = {'T','a','o','z','h','i','\0'};
char apply[] = {' ',' ',' ',' ','\0'};
就可以了.

char c[4] = {'T','a','o','\0'};
char t[] = {'T','a','o','\0'};
char t2[] = {'T','a','o','z','h','i','\0'};
char apply[] = {' ',' ',' ',' '