【问题标题】:adding char[] to dynamic array and deallocate from a function将 char[] 添加到动态数组并从函数中释放
【发布时间】:2021-07-14 02:43:42
【问题描述】:

我需要一些帮助,因为我是 C++ 新手,我有一个作业问题,我们应该将名称读取到 char[],然后将该输入放入动态数组中,对动态数组进行排序,然后终止分配的内存。我们必须使用一个完成了一半的编写程序,我不认为我在动态数组中输入不正确,并且我在释放内存时遇到问题,有人可以提供一些提示吗?我对代码的贡献在 ** 中突出显示 ** 谢谢!

const int BUFLEN = 100; // Max length of reading buffer

void sort(char* friendList[], int n); // n is the number of elements
void print(char* friendList[], int n); // n is the number of elements
void terminate(char* friendList[], int n); // n is the number of elements

const int AMOUNT = 5;

int main()
{
    char* friends[AMOUNT]; // Dynamic array with AMOUNT pcs of string pointers
    char buff[BUFLEN] = { "" }; // Creates a string buffer (null terminated)
    int count = 0;

    while (count < AMOUNT) // enter AMOUNT number of friends
    {
        cout << "Name a friend: ";
        cin.getline(buff, BUFLEN); // Temporary reading into string buffer

        friends[count] = **new char[AMOUNT];**  //. . .  WRITE CODE allocating memory to the string
        
        // WRITE CODE that adds loaded name to current location in the dynamic array
        **strcpy(friends[count], buff);**
            ++count;
    }

    sort(friends, count); // Sorts the ‘count’ strings
    print(friends, count); // Prints the ‘count’ first names
    terminate(friends, count);// Releases all allocated memory space

    return 0;
}

void sort(char* friendList[], int n)
{
    // WRITE FUNCTION that sorts the strings in the friendList in alphabetical order!
    **int result;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - 1 - i; j++)
        {
            result = strcmp(friendList[j+1], friendList[j]);
                if (result < 0)
                    swap(friendList[j+1], friendList[j]);
        }
    }**
}

void print(char* friendList[], int n)
{
    // WRITE FUNCTION that prints ‘n’ names from the friendList on screen!
    **for (int i = 0; i < n; i++)
    {
        cout << friendList[i] << " " << i << endl;
    }**

}

void terminate(char* friendList[], int n)
{
    // WRITE FUNCTION that releases all dynamically allocated memory!
    **for (int i = 0; i < n; i++)
    {
        delete friendList[i];
    }
    delete [] friendList;
    cout << "deleted! ";**
}

【问题讨论】:

  • 这是一个很好的例子,说明为什么我们应该永远教新程序员动态内存分配。这个作业没有什么是编程或计算机科学的基础,也不是 C++ 的惯用语,整件事实际上是一个“你能读懂 C++ 标准吗”的练习,但对初学者来说是强制性的。
  • 建议:选择问题的一部分(最好是你需要的部分,以便让其他部分有成功的希望,但通常把所有的A-before-B都弄清楚是有经验的)并单独攻击它。很少有一个计算机程序是一个大问题,而不是一堆小问题,所以请隔离小问题并解决它们,然后采取所有小解决方案,并像乐高积木一样将它们组装成大解决方案。
  • 在这种情况下,如果没有print,您将无法验证程序的其余部分是否正常工作。但是你不能print 没有数组`,所以用你自己输入的值制作一个非常愚蠢的数组。当您可以打印它时,您可以继续让用户将项目放入数组中。或者您可以继续进行排序,因为在您完全控制的已知数组上测试排序通常要容易得多。
  • 谢谢我一直在尝试这样做,当我运行这个程序时,我可以正确排序和打印名称,但在分配内存时不确定这部分是否正确:friends[count] = new char[AMOUNT]; //. . . WRITE CODE 为字符串分配内存 // WRITE CODE 将加载的名称添加到动态数组中的当前位置 strcpy(friends[count], buff); ++count;当我稍后尝试删除 [] 时,我在堆上遇到了一些错误

标签: c++ arrays dynamic-memory-allocation c-strings function-definition


【解决方案1】:

代替这种说法

friends[count] = new char[AMOUNT];

你需要写

friends[count] = new char[strlen( buff ) + 1];

注意数组friends本身并不是动态分配的。但是它的每个元素都指向一个动态分配的数组。所以函数terminate 看起来像

void terminate(char* friendList[], int n)
{
    // WRITE FUNCTION that releases all dynamically allocated memory!
    for (int i = 0; i < n; i++)
    {
        delete [] friendList[i];
        friendList[i] = nullptr; 
    }
    cout << "deleted! ";
}

【讨论】:

  • 非常感谢弗拉德,这对您有很大帮助 =)
【解决方案2】:

我发现这段代码有一些问题:

main():

  • 在使用buff 的内容之前未验证cin.getline() 是否成功。

  • 在分配新的char[] 以存储在friends[] 中时,AMOUNT 的大小不正确。正确的大小应该是strlen(buff)+1cin.gcount()

terminate()(不要与std::terminate()混淆):

  • delete[]'ing 输入数组本身,它不是以new[] 开头分配的,因此不能是delete[]'ed。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多