C++ 复制值二维动态数组
嗨,我想用char创建一个二维动态数组。问题是我的函数将所有单词放在同一行中。动态分配不好,但我不知道如何纠正这一点C++ 复制值二维动态数组,c++,arrays,C++,Arrays,嗨,我想用char创建一个二维动态数组。问题是我的函数将所有单词放在同一行中。动态分配不好,但我不知道如何纠正这一点 void display(char** data, int length) { for (int i = 0; i < length; i++) for (int j = 0; j < data[i][j] != '\0'; j++) cout << data[i][j]; cout
void display(char** data, int length)
{
for (int i = 0; i < length; i++)
for (int j = 0; j < data[i][j] != '\0'; j++)
cout << data[i][j];
cout << endl;
}
void add(char** &data, int length, char* word)
{
if (length == 1)
{
data = new char* [length];
}
data[length-1] = new char[strlen(word)+1];
strcpy_s(*(data + length -1), strlen(word) + 1, word);
data[length - 1][strlen(word) + 1] = '\0';
}
int main()
{
char** data = NULL;
int choice = 0, length = 0; char name[80];
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); cin.getline(name, 80);
length++;
add(data, length, name);
break;
}
cout << endl << "Enter your next choice: " << endl;
}
我很确定那不是
if (length = 1)
你本想写的
if (length == 1)
<> > C++ >代码>=<代码>意味着赋值,<代码>=< /代码>意味着相等。
不过,您的代码似乎还有其他错误。您永远不会增加数据的大小。用简单的方法操作并使用std::vector
#包括
#包括
int main()
{
std::矢量数据;
int choice=0,length=0;std::string name;
cout choice&&choice!=3)
{
开关(选择)
{
案例0:
请先提取一个用于包含在问题中的。没有多余的代码,但足以让您在不做任何更改的情况下进行编译。谢谢。但我必须使用简单数组,如我的示例中所示。因此,如果您能帮助我理解为什么这不起作用,它将非常有用graceful@codingbest因为只有当您为数据分配内存时
是当length
等于1时。但实际上,每当您添加新名称时,您都需要重新分配数据。重新分配还意味着您必须将所有现有名称从旧数组复制到新的更大数组中。我可以在不使用新数组的情况下复制元素吗?您可以解释一下如何操作吗?@codingbest不,您需要一个新数组。您分配的数组具有room仅用于一个名称,因此当您添加另一个名称时,需要分配一个新数组。
if (length == 1)
#include <vector>
#include <string>
int main()
{
std::vector<std::string> data;
int choice = 0, length = 0; std::string name;
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); getline(cin, name); // read name
data.push_back(name); // add name to data
break;
}
cout << endl << "Enter your next choice: " << endl;
}