I\'m new in StackOverflow. I\'m learning C pointer now.
This is my code:
#include
#include
int alloc(int* p){
p
Everything in C is pass-by-value. This means that functions always operate on their own local copy of what you pass in to the function. Usually pointers are a good way to mimic a pass-by-reference scheme because a pointer and a copy of that pointer both contain the same memory address. In other words, a pointer and its copy both point to the same space.
In your code the issue is that the function alloc gets its own local copy of the pointer you're passing in. So when you do p = (int*) malloc (sizeof(int));
you're changing the value of p
to be a new memory address, but the value of pointer
in main
remains unchanged.
You can get around this by passing a pointer-to-a-pointer, or by returning the new value of p
.