2019-12-02 22:13:34 8 Comments
First of all I want to apologize if this is a repeated question. But I could not find any answer explaining how to do this correctly with a variable sized array.
Going straight to the code, I've got this:
void f(int[][2]);
int main(void)
{
int (*obsF)[2] = malloc(sizeof(int)); //I reserve some memory so I can pass
f(obsF); //the array to f, since I don't know
free(obsF); //its size until later working with f.
}
void f(int obsF[][2])
{
obsF = realloc(obsF, sizeof(int[5][2])); //The 5 is just as an example.
// do stuff with obsF //I won't know this number until
} //later in f.
Testing this with valgrind threw that that free(obsF);
is an invalid free().
Now, if I do the same but everything in the main function like this:
int main(void)
{
int (*obsF)[2] = malloc(sizeof(int));
obsF = realloc(obsF, sizeof(int[5][2]));
free(obsF);
}
Valgrind tests passed successfully with no errors.
I would like to know why this is happening and how to realloc my 2D array inside function and be able to free it from main correctly.
Any other better approach or solution is well received, as long as I can use obsF as a 2D array inside f and modify it as I wish and then use it in main.
Thanks.-
Related Questions
Sponsored Content
2 Answered Questions
10 Answered Questions
[SOLVED] How to Sort Multi-dimensional Array by Value?
- 2010-04-23 13:54:26
- stef
- 762624 View
- 1061 Score
- 10 Answer
- Tags: php arrays sorting multidimensional-array
18 Answered Questions
[SOLVED] With arrays, why is it the case that a[5] == 5[a]?
- 2008-12-19 17:01:33
- Dinah
- 95191 View
- 1572 Score
- 18 Answer
- Tags: c arrays pointers pointer-arithmetic
1 comments
@user114332 2019-12-02 22:21:56
C passes arguments by value, not by reference. When you pass the
obsF
pointer tof
and reallocate it, you change the value of theobsF
parameter in thef
function, but the variable in themain
function (which determined the parameter's initial value) still holds the old pointer, which has been invalidated by the reallocation.To fix this, you can pass a pointer to the
obsF
variable tof
, and dereference that pointer to access the variable:And then call
f
as:This way, the value of the
obsF
variable insidemain
will be updated after the call tof
and the correct pointer will be freed.@Santiago 2019-12-02 22:31:03
How would be the correct way to write the prototype of f? Because I cannot get it to work.
@user114332 2019-12-02 22:35:14
I changed the example to use a plain
int *
instead ofint (*)[][]
; it should compile now.@Santiago 2019-12-02 22:51:00
I did not see that. Thank you very much. I can then cast the array to a 2D array, and free the old one, because it's what my program needs to handle. You helped me to solve my problem.-