C++ There is a simple dynamic assignment question.

Asked 2 years ago, Updated 2 years ago, 22 views

        T *p;
        int p_size = 5;
        p = new T[p_size];
        if(cnt>p_size-1) multi(p, p_size);

    void multi(T *x, int p_size)
    {
        T *temp;
        temp = new T[p_size * 2];
        for(int i = 0; i< p_size; i++)
        {
            temp[i] = x[i];
        }
        this->p_size = p_size * 2;

        delete[] x; 

        x = temp;

    };

Use it when you want to increase it to dynamic allocation due to insufficient memory. void multi creates a temp with twice the memory and puts all the data of x in the temp. Then delete x and set the address that x points to as temp.

If you print it out, the existing content of x becomes a garbage value. What should I do?

c++

2022-09-21 23:06

1 Answers

void multi(T *x, int p_size)

In , factor x is the variable that copied the pointer. The value that x points to can be the IN/OUT property, but x (pointer) is a replicated value and does not change where called, even if you change it within the multi function.

If you want to change it, try changing it to a reference type.

void multi(T *&x,int p_size);


2022-09-21 23:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.