Here is the sample program
# include <stdio.h>
# include <stdlib.h>
// COMPILER : GNU GCC COMPILER
// EDITOR : CODE::BLOCKS 8.02
struct test
{
int data;
struct test *link;
};
void change(struct test *ptr);
int main()
{
struct test *fresh = (struct test *)malloc(sizeof(struct test));
int some_data = 10;
fresh -> data = some_data;
fresh -> link = NULL;
printf("\n\n\tBefore Going Into Function");
printf("\n\n\tData = %d\t\tAddress %x", fresh -> data, fresh);
printf("\n\n\t____________________________________________________________");
change(fresh);
printf("\n\n\tAfter Getting Out Of Function");
printf("\n\n\tData = %d\t\tAddress %x", fresh -> data, fresh);
printf("\n\n\t____________________________________________________________");
return 0;
}
void change(struct test *some_ptr)
{
struct test *new_fresh = (struct test *)malloc(sizeof(struct test));
some_ptr = new_fresh;
int some_new_data = 20;
new_fresh -> data = some_new_data;
new_fresh -> link = NULL;
printf("\n\n\tInside Function");
printf("\n\n\tData = %d\t\tAddress %x", some_ptr -> data, some_ptr);
printf("\n\n\t____________________________________________________________");
}
And this is the output
Before Going Into Function
Data = 10 Address 3d2488
____________________________________________________________
Inside Function
Data = 20 Address 3d2508
____________________________________________________________
After Getting Out Of Function
Data = 10 Address 3d2488
____________________________________________________________
Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.
Hence, we see that the original structure variable is not changed.
So my question is how do i send the reference of the structure variable so that my output becomes
Before Going Into Function
Data = 10 Address 3d2488
____________________________________________________________
Inside Function
Data = 20 Address 3d2508
____________________________________________________________
After Getting Out Of Function
Data = 20 Address 3d2508
____________________________________________________________
Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.
I tried the concept of using &
in the actual parameter and **
in the formal parameter but it gave errors.
BTW, i can't return the structure variable. It is a requirement of the program. (It's not a homework assignment, I'll use this concept in DEQUE by returning both head and tail of the list)
Thanking in advance