Luca
Luca

Reputation: 595

Passing Pointer to Function Only Changes Value in Function Scope

It seems I am doing something wrong in passing these pointers as arguements to my getImages function. Testing my code showed that in the function getImages, my pointers home and start were able to take on appropriate values. But testing them again back in main scope their values were both 0. I have included the relevant code snippets below. Please tell me how I can correctly pass these arguments. Thank you.

void getImages(IplImage *home, IplImage *start);

int main(int argc, char **argv)
{
    IplImage *home = 0;
    IplImage *start = 0;

    getImages(home,start);

Upvotes: 1

Views: 776

Answers (2)

Richard Vu
Richard Vu

Reputation: 320

Pointers are variables that hold addresses. If you pass in pointers to getImages then you should dereference those pointers to access the actual object. However since you've set your home and start pointers to 0, no memory was allocated to the IplImage object and therefore it doesnt exist. As a result, derefencing non-allocated memory will cause your compiler to complain.

You should pass in by reference:

void getImages(IplImage &home, IplImage &start)
{
    // do something with home
    // do something with start
}

int main(int argc, char **argv)
{
    IplImage home;
    IplImage start;

    getImages(home,start);
}

Note above that IplImage is allocated memory on the stack since references can't be null, unlike pointers, references need memory allocated prior to use.

Hope that helps.

Upvotes: 0

yizzlez
yizzlez

Reputation: 8805

You must pass the pointers by reference:

void getImages(IplImage *&home, IplImage *&start);

Upvotes: 2

Related Questions