首页 > 解决方案 > 复制先例值二维动态数组

问题描述

嗨,我想使用 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

标签: c++arrays

解决方案


我很确定,而不是

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;
    }

问题解决了。


推荐阅读