c++ - 复制先例值二维动态数组
问题描述
嗨,我想使用 char 创建一个 2d 增长的动态数组。问题是我的函数将所有单词放在同一行。动态分配不好,但我不知道如何纠正。
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;
}
这就是得到
Enter your choice
0
Enter name to add:
jhon
jhon
Enter your next choice:
0
Enter name to add:
marc
jhonmarc
解决方案
我很确定,而不是
if (length = 1)
你打算写
if (length == 1)
在 C++=
中意味着赋值和==
相等。
似乎您的代码还有其他错误。你永远不会增长data
. 做简单的方法和使用std::vector<std::string>
#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;
}
问题解决了。
推荐阅读
- css - vscode中预期的CSS错误规则或选择器
- javascript - 如何在我的 laravel 项目中添加自定义 javascript 文件?
- postgresql - 使用旧的触发器动态获取列名
- c++ - 如何设置 CMake 以构建包含路径包含的代码,例如#include
? - python - 具有时间序列的纸浆优化运输
- powershell - 如何通过powershell编辑chrome中现有的标签url?
- android - DeepLinking 工作,但没有使用反应导航导航到预期屏幕
- javascript - LeafLetJS 快速入门指南显示灰色(401 未经授权)
- google-app-engine - 将子域映射到 GAE 应用程序的问题
- ios - 为什么我在 Swift5 中收不到推送消息?