I am trying to make a simple piece of c code using pointers work but memory is being overwritten unexpectedly.
I want to create an array of pointers to integers then create a pointer to an integer and assign it's address to an array.
Therefore, the array will point to a pointer to an integer. I did this in a function called add_value_to_array().
Here is my code :
void add_value_to_array(int *** array, int * value) {
*array = &value;
}
int main() {
int ** arr = { 0 };
int value = 5;
int * value_ptr = &value;
add_value_to_array(&arr, value_ptr);
//arr = &value_ptr;
printf("looool\n");
printf("looool\n");
printf("looool\n");
printf("looool\n");
printf("%p\n", arr[0]);
}
What I want is :
arr -> value_ptr -> 5
(arr = &value_ptr
*array = value_ptr
value_ptr = &value
*value_ptr = 5
**arr = 5)
however, this is what I have right after add_value_to_array() is called, but memory is overwritten when I call the printfs(), I get garbage values in my arr variable.
Even weirder, if I do directly arr = &value_ptr instead of calling add_value_to_array, things go as expected and memory is not overwritten by the printfs().
So it seems that memory is allocated differently if I use a function or if I do I do things outside of it.
What is happening that I am seeing this behavior?