gpt4 book ai didi

c++ - 为什么我不能在结构中初始化char数组?

转载 作者:太空狗 更新时间:2023-10-29 20:20:18 24 4
gpt4 key购买 nike

typedef struct book {

int a;
int b;
char cb[100];

book(int a1, int b1, char* cb1) {
a = a1;
b = b1;
cb = cb1;
}

} book;

为什么我不能将 cb 初始化为 cb1 以及如何在没有 strcpy 的情况下进行初始化?

最佳答案

Why can't I initialise cb to cb1 and how to do it without strcpy?

cb1char* 类型,但是 cb 是 C 风格的数组,也就是正式的数组类型的对象(这个特别是 char[100])。 Objects of array type cannot be modified (即使它们是左值)。如果你只想浅拷贝而不是你说的strcpy(),那么你可以将cb定义为char* 而不是 char[100]:

typedef struct book {

// ...
char* cb;

book(int a1, int b1, char* cb1) {
// ...
cb = cb1;
}

} book;

但在大多数情况下我不建议这样做,因为这会导致对原始指针的不稳定管理。这被标记为 [C++],有什么理由不使用 std::string


注意:虽然您没有标记此 [C++11] 或更高版本,但进一步的理由是不使用此类原始指针或像这样的 C 样式数组是当您尝试使用上述结构时会发生的情况,可能像这样:

int main() {
book b(4, 2, "Hello");
return 0;
}

像 Clang 这样的标准编译器会立即让您知道1:

ISO C++11 does not allow conversion from string literal to 'char *'.

这种从字符串文字 ( the type of which is const char[] ) 到char* 的隐式转换甚至在 C++03 中也被弃用了,现在 completely removed since C++11.

1 默认情况下,这至少会是一个警告,并且在使用 -pedantic-errors 构建时会出现错误。

关于c++ - 为什么我不能在结构中初始化char数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52215936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com