char []和char [10](或任何其他任意常量)之间有什么区别吗?
例如:
char[] = "here";
char[10] = "there";
Run Code Online (Sandbox Code Playgroud)
当我运行这样的程序时:
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char elem;
};
void BinaryTreeFromOrderings(char* ,char* ,int);
int main()
{
char a[] = "";
char b[] = "";
cin >> a >> b;
BinaryTreeFromOrderings(b, a, strlen(a));
return 0;
}
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
if(length == 0) return;
TreeNode* node = new TreeNode;
node->elem = *preorder;
int rootIndex = 0;
for(;rootIndex < length ; rootIndex ++)
{
if(inorder[rootIndex] == *preorder)
break;
}
//left
BinaryTreeFromOrderings(inorder,preorder+1,rootIndex);
//right
BinaryTreeFromOrderings(inorder + rootIndex +1 ,preorder + rootIndex +1,length - (rootIndex + 1));
cout << node->elem;
delete [] node;
return;
}
Run Code Online (Sandbox Code Playgroud)
结果似乎是正确的,但程序将在退出之前转储.
然后我做了一个实验:
int main()
{
char a[] = "";
cin >> a;
cout << a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入少于9个字符时,它将成功运行.(gcc版本4.6.3(Ubuntu/Linaro 4.6.3-1ubuntu5))
如果我使用以下内容初始化[]:
char a[] = "123456789";
Run Code Online (Sandbox Code Playgroud)
它的成功不到25个特征.
我猜有些东西,编译器无法确定a的大小.但具体原因是什么?
char[] = "here";
Run Code Online (Sandbox Code Playgroud)
这是一个大小为5的数组,自动从4个字母中推导出来,加上一个隐含的空终结符('\ 0')加在最后.您可以从0-4位置进行书写和阅读.其他任何东西都是未定义的行为.
char[10] = "there";
Run Code Online (Sandbox Code Playgroud)
这是一个数组大小为10的内容"there\0\0\0\0\0"
.您可以从0-9位置进行书写和阅读.其他任何东西都是未定义的行为.
char a[] = "";
Run Code Online (Sandbox Code Playgroud)
这是一个大小为1的数组,只是一个空终止符.当你输入9个字符时,这是未定义的行为.(实际上,使用标准字符串输入函数,您甚至无法安全地输入1个字符,因为标准字符串输入函数会自动添加到null终止符上.
char a[] = "123456789";
Run Code Online (Sandbox Code Playgroud)
这是一个大小为10的数组,当你输入25个字符时,这是未定义的行为.
http://en.wikipedia.org/wiki/Undefined_behavior