C ++,为什么array = ptr legal? [英] C++, why is array=ptr legal?

查看:138
本文介绍了C ++,为什么array = ptr legal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我看到这段代码。此行是否是编译错误? char arr [4] =Abc;



是arr是指针吗?是char *复制到堆栈中的数组吗?这是合法的在所有版本的C + +(和什么关于C?)。我测试和看到这个工作在VS和代码垫,我相信使用gcc



-edit-只是为了乐趣,我试图用静态const char *替换Abc。它给我一个无效的初始化程序错误。

  int main()
{
int j = 97;
char arr [4] =Abc;
printf(arr,j);
getch();
return 0;
}


解决方案

array = ptr 不是合法赋值(如果数组有数组类型并且 ptr 具有相应的指针类型)。在你已经显示的代码中, = 引入了一个初始化器,因为它是一个声明的一部分。



使用字符串常量初始化 char 的数组是合法的。 p>

Recently i saw this piece of code. Shouldnt this line be a compile error?char arr[4]="Abc";

What happens here? Is arr a pointer? is the char* copied into an array on stack? is this legal in all version of C++ (and what about C?). I tested and seen this works in VS and code pad which i believe uses gcc

-edit- Just for fun I tried replacing "Abc" with a static const char *. It gave me an invalid initializer error.

int main()
{
    int j=97;
    char arr[4]="Abc";
    printf(arr,j);
    getch();
    return 0;
}

解决方案

array = ptr is not a legal assignment (if array has an array type and ptr has the corresponding pointer type). In the code you have shown, though, the = introduces an initializer as it is part of a declaration. It is not an assignment.

It is legal to initialize an array of char with a string constant.

这篇关于C ++,为什么array = ptr legal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆