I will give a simple example inspired from my problem :
void change(int *x, int *y){x=y;}
int main(){
int *xx,*yy;
yy = (int*)malloc(sizeof(int));
change(xx,yy);
if(xx == NULL)printf("is null\n");
else printf("---- %d ----\n",*xx);
.................................................. .........
xx doesn't point to the value of yy (*yy) , the program prints "is null" . Why ?
xx and yy must be declared int* , it's something that i must do in my program .
|
Mentor
|
![]() |
| 26Oct2008,16:15 | #2 |
|
A quick lesson on pointers. If a function has to change something that is passed in, then you need to pass in a pointer to that thing. For example,
Code:
void add1(int x)
{
x=x+1;
}
int main()
{
int var;
add1(var);
}
Code:
void add1(int *x)
{
*x=*x+1;
}
int main()
{
int var;
add1(&var);
}
The same is true for pointers, if you need to modify a pointer, then you have to pass in the address of that pointer. So: Code:
void incr_ptr(int *x)
{
x=x+1;
}
int main()
{
int x[2];
int *x_ptr=&x[0];
incr_ptr(x_ptr);
}
Code:
void incr_ptr(int **x)
{
*x=*x+1;
}
int main()
{
int x[2];
int *x_ptr=&x[0];
incr_ptr(&x_ptr);
}
Code:
void change(int **x,int *y)
{
*x = y;
};
int main()
{
int *xx, *yy;
yy=malloc(sizeof int);
change (&xx,yy);
//etc
Despite the simplicity of the program there are still two bugs worth a mention: The value displayed by the program will be unpredictable, because *yy is uninitialised. Also, the program leaks memory, because the malloc() is not matched by a free(). Both these are major bugs; a memory leak in a long running program will mean that the program will eventually stop working because there's no memory left, and uninitialised variables will mean any behaviour dependent on the value of those variables will be unpredictable. So some good habits for you to develop immediately are: - ALWAYS initialise variables. Initialise them to zero if you can't think of a suitable value. - ALWAYS ALWAYS ALWAYS initialise pointers. Initialise them to zero. - ALWAYS write "free" somewhere, ideally in such a way as to cause a compiler error, when you write malloc(), because that will force you to deal with the free at the most important time (same is true for new/delete/new[]/delete[] in C++). Leaving it will mean that you forget it, which means (a) you'll get a leak and (b) you'll have to spend hours trying to find what is leaking. ALWAYS write resource allocation and resource deallocation simultaneously, or as simultaneously as possible. - Remember that allocating memory simply gives you somewhere to stuff a value. It doesn't do any value stuffing for you. int **yy=malloc(sizeof int); initialises yy to point to an int, but the int it points to is NOT DEFINED.
jose_peeterson
like this
|

