【问题标题】:SIGSEGV, Segmentation faultSIGSEGV,分段错误
【发布时间】:2014-11-24 17:35:00
【问题描述】:

我是 C++ 新手(从我的代码中可以看出),我正在练习使用指针和数组以及我的结构进行动态内存分配。我的代码工作正常,直到它访问“growArray”函数,然后它给了我 SIGSEGV 错误。我不知道为什么,因为据我所知,我正确地传递了一个指向指针的指针,而且我还为新指针分配了空间。是我的结构有问题,还是传递指针有问题,还是接收指针有问题?我希望这个问题有意义。

#include <iostream>
#include <string>

using namespace std;

struct FriendInfo
{
  string name;
  string address;
  string number;
};

FriendInfo *growArray(FriendInfo *p_entry, int *size);

int main()
{
    int curNum = 0;
    int size = 2;
    int userAnswer;
    FriendInfo *p_friends = new FriendInfo[size];

    cout << "Enter a friend's info?(1 for yes, 0 for no)\n";
    cin  >> userAnswer;
    while (userAnswer != 0)
    {
        if (curNum == size)
        {
            p_friends = growArray (p_friends, &size);
        }
        cout << "What is your friend's name?\n";
        cin  >> p_friends[curNum].name;
        cout << "What is your friend's address?\n";
        cin  >> p_friends[curNum].address;
        cout << "What is your friend's number?\n";
        cin  >> p_friends[curNum].number;
        curNum++;
        cout << "Enter another friend? (1 for yes, 0 for no)\n";
        cin  >> userAnswer;
    }
}

FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
    *size *= 2;
    FriendInfo *p_new_friends = new FriendInfo[*size];
    for (int i = 0; i < *size; ++i)
    {
        p_new_friends[i] = p_entry[i];
    }
    delete [] p_entry;
    return p_new_friends;
}

【问题讨论】:

  • 必答题——你为什么不使用std::vector
  • @PaulMcKenzie:因为他正在训练如何手动驾驶?
  • 他确实明确表示他正在练习 DMA :)

标签: c++ arrays pointers function-pointers dynamic-programming


【解决方案1】:

您的问题是您将size 的值加倍,即使p_entry 是初始size。将代码更新为:

FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
    int newSize = *size * 2;
    FriendInfo *p_new_friends = new FriendInfo[newSize];
    for (int i = 0; i < *size; ++i)
    {
        p_new_friends[i] = p_entry[i];
    }
    delete [] p_entry;
    *size = newSize;
    return p_new_friends;
}

【讨论】:

    【解决方案2】:

    在你的 for 循环中,一旦你达到 p_entry 的大小,而不是大小,你想停止

    FriendInfo *growArray(FriendInfo *p_entry, int *size)
    {
        int orig_size = *size;
        *size *= 2;
        FriendInfo *p_new_friends = new FriendInfo[*size];
        for (int i = 0; i < orig_size; ++i)
        {
            p_new_friends[i] = p_entry[i];
        }
        delete [] p_entry;
        return p_new_friends;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      相关资源
      最近更新 更多