每个循环指针值返回零

时间:2017-02-11 10:32:09

标签: c++ pointers

也许这是一个愚蠢的问题,但是在将值返回指针后一切都很好,当while循环再次启动时,指针的值返回零

以下是代码:

int num;
    int size = 0;
    int **p = 0; /*Or 0*/

    while (true) {
        cout << "Choose number:\n\n";
        cout << "1- Print array\n";
        cout << "2- Enter new row to array\n";
        cout << "3- Delete a row from array\n";
        cin >> num;
        switch (num)
        {
        case 1:
            Print(p, size);
            break;
        case 2:
            p = Add(p, size);
            size++;
            break;
        case 3:
            p = Delete(p, size);
            size--;
            break;
        }
    }

为什么指针值消失了?

Edite:

我调试了代码,p的值很好,直到循环再次启动,然后返回null。 AddDelete函数:

int **Add(int **pm, int size) {

    int arr[6];
    cout << "Enter 6 new elements to the row: ";
    for (size_t i = 0; i < 6; i++)
    {
        cin >> arr[i];
    }
    int **tmp = new int*[size + 1];

    for (size_t i = 0; i < size; i++)
    {
        tmp[i] == pm[i];
    }
    delete[]pm;
    pm = tmp;
    pm[size] = arr;

    return pm;
}

int **Delete(int **pm, int size) {
    int num;
    cout << "Enter row number to delete:";
    cin >> num;

    int**tmp = new int*[size - 1];
    for (size_t i = 0, j = 0; i < size - 1; i++)
    {
        if (i != num)
        {
            tmp[j] = pm[i];
            j++;
        }
    }
    delete[]pm;
    pm = tmp;

    return pm;
}

0 个答案:

没有答案