初始化程序无效

时间:2012-01-01 16:44:47

标签: c++

此代码一直说:错误:初始化程序无效

char * ss = "hello world";
char s[10] = ss;
std::transform(s, s + std::strlen(s), s, static_cast<int(*)(int)>(std::toupper));

如何解决?

4 个答案:

答案 0 :(得分:2)

带有C字符串的数组的初始值设定项无效。好消息是你根本不需要它:

char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
cerr << s << endl;

请注意,我为s数组填充了一个额外的元素,用于终止零。

答案 1 :(得分:1)

char s[10] = ss;

这会尝试将数组的值设置为等于指针,这没有任何意义。另外,十个字节不够(在C风格的字符串的末尾有一个终止的零字节)。尝试:

char s[20];
strcpy(s, ss);

答案 2 :(得分:0)

您无法为数组指定指针,因为您无法将任何内容分配给数组,而是指定初始化列表。您需要将字符从ss复制到s。此外,大小为10的数组太小而无法容纳"hello world"。例如:

char * ss = "hello world";
char s[12] = {}; // fill s with 0s

strncpy(s, ss, 11); // copy characters from ss to s

或者,您可以

char s[] = "hello world"; // create an array on the stack, and fill it with
                          // "hello world". Note that we left out the size because
                          // the compiler can tell how big to make it

                          // this also lets us operate on the array instead of
                          // having to make a copy

std::transform(s, s + sizeof(s) - 1, s, static_cast<int(*)(int)>(std::toupper));

答案 3 :(得分:0)

您的阵列分配是非法的,如果是您的代码,则首先不需要。

const char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
相关问题