Reputation: 628
So I was playing around with some pointer today and ran into a rather confusing predicament. I use C a lot but couldn't seem to figure out why this wouldn't work maybe its just one of those days.
#include <stdio.h>
#include <stdlib.h>
void subr(int* numero){
int* newNum = malloc(sizeof(int));
(*newNum) = 5;
numero = newNum;
printf("%d\n", *numero);
}
int main(){
int* number;
printf("%p\n", (void *) number);
subr(number);
if(number == NULL)
printf("Not assigned\n");
else
printf("%d\n", *number);
}
So I create a pointer in main, pass it into a function which allocates space and then assigns it back to the pointer passed in. Why is it that everytime I run this I get that the pointer is still null?
Upvotes: 0
Views: 112
Reputation: 726479
The reason that this code does not work is that C is a pass-by-value language. If you wish to modify anything, you have to pass a pointer to it:
void subr(int** numero){
int* newNum = malloc(sizeof(int));
(*newNum) = 5;
*numero = newNum;
printf("%d\n", **numero);
}
int main(){
int* number = NULL; // <<== Need to initialize it
printf("%p\n", (void *) number);
subr(&number);
if(number == NULL)
printf("Not assigned\n");
else
printf("%d\n", *number);
free(number); // <<== Don't forget to free what's malloc-ed
}
Upvotes: 4