Search code examples
c++pointersvectorstructdynamic-memory-allocation

C++ : Using a int pointer to point to a vector created inside a function


I am still perfecting the art of posting here so bear with me, I will edit and fix anything suggested!

I have a homework that requires me to create functions that manipulate vectors. The "catch" is that all the data passed to the function is passed by reference to this struct:

struct Vector { // this struct must stay as is
    int sze = 0; // "size" took out i for compatability
    int capacity = 0;
    int * data = nullptr ;
}a,b,c;

i.e.

void construct_vector ( Vector& v, int size= 0, int initVal= 0);

The problem that I am having is in the function construct_vector() I have to, you guessed it, construct a vector and use int* data to point to the vector on the heap? I am not positive about that last part). I just know I have to use the int pointer to point to the vector created within the construct function, and cannot for the life of me figure out how to do that.

An example of what I am trying:

void construct_vector ( Vector &v, int size, int initVal){

    std::vector<int> t(size,initVal);
    *v.data = &t ; // ERROR: Assigning to 'int' from incompatible type 'std::vector<int> *'
    v.capacity = size; //
    v.sze = size;

    for (int i=0; i < t.size(); i++){
        /* I originally tried to implement a
        dynamic int pointer here but I cannot change int* data
        to int*data[sze] within the struct*/
    }
}

The reason int * data must point to the vector is because the data is passed to the subsequent functions by reference to struct member v:

void destroy_vector ( Vector & v );
void copy_data ( Vector & v );

Edit: My problem was that I misunderstood the objective of my assignment but I think the answers I received can really help people understand dynamic memory and how it should be used within functions. So I am going to leave everything as is!


Solution

  • You have two problems here:

    std::vector<int> t(size,initVal); 
    *v.data = &t ; // ERROR: Assigning to 'int' from
    

    First, *v.data and &t are different types, one is int, the other is a pointer to a vector of ints.

    You can get it compile with (but you SHOULD NOT, see the second problem)

    v.data = t.data();
    

    The other problem is the vector is local to the function. As soon as the function returns, your pointer will dangle.

    So the right solution for your problem is using a dynamic array:

    v.data = new int[size];
    

    Don't forget to delete[] it in the struct's destructor when you are done using it:

    delete [] data;