jde*_*dex 2 c++ arrays initialization
假设我有一个char数组,这没关系:
char myChars[100] = "hello";
Run Code Online (Sandbox Code Playgroud)
但如果我有一个
const char* hello="hello";
char myChars[100] = hello;
Run Code Online (Sandbox Code Playgroud)
要么
const char hello[6]="hello";
char myChars[100] = hello;
Run Code Online (Sandbox Code Playgroud)
这不被允许:
error: array must be initialized with a brace-enclosed intializer
Run Code Online (Sandbox Code Playgroud)
在我看来,这些基本上是等价的陈述,为什么会这样呢?
因为指针不是数组,而数组不是指针.
这些例子并不等同; 字符串文字"hello"不是指针,而是a const char[6],可用于初始化您char myChars[100]的特殊情况.
但是,如果你首先让它衰减到一个指针,那么你以后就不能再回到那个数组了.在一般情况下,编译器无法知道数组的大小,或者甚至是一个数组.因此,无论以前发生什么,从指针初始化数组都是无效的.
您需要区分指针和数组。
下面定义了一个指向常量文本的指针:
const char* hello="hello";
下面定义了一个数组:
char myChars[100];
您正在尝试将指针分配给数组的单个槽:
char myChars[100] = hello;
你最好的选择是使用std::string.
在嵌入式编程中,我经常使用:
static const char hello_text[] = "Hello";
我让编译器确定数组的大小。