student student - 2 months ago 5
C++ Question

correctly declare pointers, allocate memory, and send them as parameters c++

How correctly declare pointers, allocate memory, and send them as parameters in fuctions to write values. The bellow part of code is what I tried but it doesn't work correctly. I need the same logic, I mean declare, set, show

...

struct complex {
int i;
int r;
};

void set(complex *n, int i, int r){
n = new complex;
n->i = i;
n->r = r;
}

void show(complex *n){

std::cout << n->i << " " << n->r;
}

int main(int argc, char* argv[])
{
complex *n;
set(n,10,20);
show(n);
system("pause");
return 0;
}

Answer

Actually, your function set couldn't work, because by doing

n = new complex;

whatever the pointer you pass to the function, the pointer will be overwritten by the pointer on the new object.

  • You can pass the pointer via reference (on C++ only...) like that

    void set(complex* &n, int i, int r)

And by doing so you'll modify the value of the original pointer.

  • You can also simply return the pointer by a return n But obviously if the prototype of your function must stay like that, it's not possible...

  • Or you can use a double pointer, but it's a bit tricky ! If I don't make mistake, you create a

    complex** n

You pass it to your function

`set(complex** n, int i, int r)`

And then you load

*n = new complex

And it must work if you pass *n to all your function instead of n...

And don't forget to delete your object at the end ;)

Comments