I have tried two ways to create a structure in a function, and then return its starting address to the main function.
One way is to use malloc within the function and then return the address back to main. (pt1 and testFunction1() below)
The other way is to simply create the structure within the function and then pass the address back to main. (pt2 and testFunction2() below).
Both options seem to work fine. However, I have an intuitive feeling that the second option is not correct (partly because the the first method is used in my textbook).
Can someone explain to me if and why the malloc way is better?
Code:
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int i;
};
struct Test *testFunction1();
struct Test *testFunction2();
void changeValue(struct Test *);
int main (void)
{
struct Test *pt1;
struct Test *pt2;
pt1 = testFunction1();
printf("%d\n", (*pt1).i);
pt2 = testFunction2();
printf("%d\n", (*pt2).i);
changeValue(pt1);
printf("%d\n", (*pt1).i);
changeValue(pt2);
printf("%d\n", (*pt2).i);
return 0;
}
struct Test *testFunction1()
{
struct Test *pointer;
pointer = (struct Test *) malloc( sizeof(struct Test) );
pointer->i = 1234;
return pointer;
}
struct Test *testFunction2()
{
struct Test *pointer;
struct Test structure1;
pointer = &structure1;
structure1.i = 9876;
return pointer;
}
void changeValue (struct Test *pointer)
{
pointer->i = 55555;
return;
}
/* OUTPUT
1234
9876
55555
55555
*/