The first problem is that you are relocating the object and playing on the variable r
who dies there. It seems he wants to play in po
even to reflect on array
in the calling function.
But then we find another problem, you don’t want to pass the object but the pointer to the object, so you must pass &array
to grab a pointer to array
, which happens to be a pointer. And of course, the parameter should receive a pointer to what it will receive, so it should be a pointer to another pointer. And the right guy over there is uint8_t
.
Fixing these problems you pass a memory address to a function, it will be changed to another address and as it went by reference it is changed in the variable that served as argument, which is what you want.
I hope this is just to demonstrate the mechanism because in real code it doesn’t make much sense to do this.
The way it was nothing was changed into array
that kept pointing to null.
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
void a(uint8_t **po, size_t t) {
*po = realloc(*po, t);
}
int main() {
uint8_t *array = NULL;
a(&array, sizeof(uint8_t) * 2);
array[0] = 1;
array[1] = 3;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero