我有一个程序,它:
- 创建一个包含 3 个
char
指针的数组,char *z_str[3];
. - 分配类型为
char
的动态内存对象,并将返回的指针分配给这些char
指针。 - 提示用户提供输入字符串。
- 打印提供的字符串。
源代码:
#include <iostream>
using namespace std;
int main()
{
char *z_str[3];
int i;
for(i = 0; i < 2; i++)
{
z_str[i] = new char [30];
if(z_str[i] == NULL)
{
cout << "Memory for String " << i+1 << " could not be allocated!" << endl;
cout << "Program terminates.";
return 1;
}
}
cout << endl << endl;
cout << "Please input the first string [max.29 characters]:" << endl;
cin >> z_str[0];
cout << endl;
cout << "Please input the second string [max.29 characters]:" << endl;
cin >> z_str[1];
cout << endl;
cout << "Please input the third string [max.29 characters]:" << endl;
cin >> z_str[2];
cout << endl << endl;
cout << "First string is:" << endl;
cout << z_str[0] << endl << endl;
cout << "Second string is" << endl;
cout << z_str[1] << endl << endl;
cout << "Third string is:" << endl;
cout << z_str[2] << endl << endl;
return 0;
}
当我在 Linux Ubuntu 中使用 g++ 编译此代码并运行代码时,当程序将char
字符串打印到 CLI 中时,我遇到了分段错误。
端子输出:
Please input the first string:
string1
Please input the second string:
string2
Please input the third string:
string3
Segmentation fault (core dumped)
现在,如果我在Windows 10中使用g ++/MingW编译相同的代码,那么一切都可以在PowerShell中正常工作:
Please input the first string:
string1
Please input the second string:
string2
Please input the third string:
string3
First string is:
string1
Second string is
string2
Third string is:
string3
- 为什么我在 Linux Ubuntu 中打印字符字符串时遇到 g++ 的分段错误,而在 Windows 中的 g++/MingW 中却没有出现C++?
循环
for(i = 0; i < 2; i++)
会让你初始化z_str[0]
和z_str[1]
,但不会z_str[2]
。
因此,当您在z_str[2]
中使用未初始化和不确定的值时,您会得到未定义的行为(和崩溃(。
您需要增加循环以迭代所有元素:
for(i = 0; i < 3; i++)
所有这些都有更好的解决方案,我建议使用std::string
对象的std::array
:
std::array<std::string, 3> z_str;
现在你不需要自己做任何动态分配,数组中的所有三个字符串都将是默认构造的,这意味着它们将是空(但有效(的字符串。
如果您不允许使用std::array
或std::string
,还有其他方法可以改进您的程序,例如使用范围for
循环:
for (auto& str_ptr : z_str)
str_ptr = new char[30];
上面的循环保证遍历数组的所有元素。