0

In the main function, I have some null pointer like

double *data_1;

This pointers are passed as argument to other function which determine how many components must have data_1 and uses malloc to assign a memory block and store information:

void function(double *data) {
   ...

   data = (double *) malloc((size_t) (Ndata) * sizeof(double));

   for(i = 0; i < (Ndata); i++) {
     data[i] = sys->points[i][coordinate];
  }
}

This code isn't working. I used GDB to examine bug and I encounter that inside function() the assignment works, but when execution returns to the main() function, the array data_1 wasn't modified although the memory to which it points is exactly the same to which points "data" argument in function().

Why is this happening?

3
  • double *data_1; is not a null pointer, it's an uninitialised pointer. Commented Feb 23, 2018 at 10:52
  • Parameters are passed by value in C. Your function gets a value of the pointer from its caller, not the reference to the caller's variable. Commented Feb 23, 2018 at 10:53
  • If I declare double *data_1=NULL then in the main() it happens that I can't access to the "new components" of data_1 Commented Feb 23, 2018 at 10:58

1 Answer 1

2

The pointer you passed to your function is passed by value. It is copied to the parameter data. Inside you are allocating memory to data which will make it to point to the allocated memory instead of the pointer you passed. Any modification done to this pointer is not reflected to the pointer you passed. You need to return the pointer to the allocated memory.

double *function() {
   ...

   double *data = malloc((size_t) (Ndata) * sizeof(double));

   for(i = 0; i < (Ndata); i++) {
     data[i] = sys->points[i][coordinate];
   }
   return data;  
}
Sign up to request clarification or add additional context in comments.

7 Comments

This probably eliminates the point of passing the data pointer in the first place (and allows incorrect usage by simply discarding the result).
@Groo; Well agree with your view but the code has nothing wrong. I will fix it though. Regarding incorrect uses, it is programmers responsibility to use the function correctly. There are 100s of libraries in which 10000s of methods returns pointer to some object.
Nothing wrong with the code, just a comment, I didn't downvote.
@Groo I undid ^^
Thanks everybody! I didn't understand, but this is the answer: Initializing a pointer in a separate function in C
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.