Hy everyone,
pls consider this small code, and help me to figure out, why it's not working?
#include <stdio.h>
#include <stdlib.h>
void setup(int* helo) {
helo = (int*) malloc(sizeof(int));
(*helo) = 8;
}
int main(int argc, char* argv[]) {
int* helo = NULL;
setup(helo);
printf("Value: %s \n", (*helo));
getchar();
return 0;
}
You are looking for one of two options here. You can either take the memory pointer allocation out of the equation, and pass the memory address of a standard variable:
void setup(int* helo)
{
*helo = 8;
}
int main(int argc, char* argv[]) {
int helo = 0;
setup(helo);
printf("Value: %d\n", helo);
getchar();
return 0;
}
Or, if you want to stick with your approach, the signature of your function needs to change to receive a pointer to a pointer:
void setup(int** helo) {
*helo = (int*) malloc(sizeof(int));
*(*helo) = 8;
}
int main(int argc, char* argv[]) {
int* helo = NULL;
setup(&helo);
printf("Value: %d \n", (*helo));
getchar();
return 0;
}
The reason for this is that setup(int* helo)
receives a copy of int* helo
declared in main()
, and this local copy will point to the same place. So whatever you do with helo
inside setup()
will be changing the local copy of the variable and not helo
from main()
. That's why you need to change the signature to setup(int** helo)
.