简体   繁体   English

无法初始化字符数组

[英]Unable to Initialize char array

Im trying to see why the following code does not work:我想看看为什么下面的代码不起作用:

void test2() {
    char ulu[256];
    ulu[]{ "Hello","Hello" };

}

But this code works:但这段代码有效:

struct my_test
{
    char test_array[256];
};

void test() {
    my_test test_array[]{ "hello", "hello" };
    printf("%s", test_array);
}

I would expect both codes to fail but only the first one does我希望两个代码都会失败,但只有第一个会失败

Can someone explain to me why it works when declaring and initializing the variable test_array as an object of the my_test class?有人可以向我解释为什么在将变量 test_array 声明和初始化为 my_test 类的对象时它会起作用吗?

Im getting an error stating:我收到一个错误说明:

a value of type "const char *" cannot be used to initialize an entity of type "char"

Thanks in advance for the help!在此先感谢您的帮助!

Since test() uses uniform initialization , it's compiled correctly.由于 test() 使用统一初始化,它被正确编译。 test2() seems doing an assignment. test2() 似乎在做任务。 You can't use uniform initialization when assignment.赋值时不能使用统一初始化。

Can someone explain to me why it works when declaring and initializing the variable test_array as an object of the my_test class?有人可以向我解释为什么在将变量 test_array 声明和初始化为 my_test 类的对象时它会起作用吗?

char ulu[256];
ulu[]{ "Hello","Hello" };

This is not the right syntax.这不是正确的语法。

What you want is something like this:你想要的是这样的:

char ulu[][256] {
  "Hello",
  "Hello"
};

for (auto const& i : ulu)
  std::cout << i << '\n';

Output:输出:

 Hello Hello

A more modern approach would use std::vector or std::array更现代的方法是使用std::vectorstd::array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM