You are allocating the memory for the struct three times, and throwing away the memory each time returning from foo()! Allocate the memory BEFORE calling foo(), and pass in the ONE instance of the struct object into foo()!
Check the return value from malloc() to insure the allocation worked correctly!
You only have to cast the pointer if you are displaying the address using %p, and NEVER cast an int to a (void *)!
A good up to date book on the C Language would have explained this and more!
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct{
int var1;
int var2;
} svar;
void foo ( svar *spvar , int fvar1, int fvar2 )
{
spvar -> var1 = fvar1;
spvar -> var2 = fvar2;
// Cast pointers to (void *), but NOT ints
printf("value %d store at memory location %p (spvar->var1) \n", spvar -> var1, (void*) &spvar -> var1 );
printf("value %d store at memory location %p (spvar->var2) \n\n", spvar -> var2, (void*) &spvar -> var2);
}
int main ()
{
svar *spvar = NULL;
// Allocate the memory BEFORE calling function foo()
spvar = malloc(sizeof(svar));
if(spvar == NULL)
{
printf("Memory allocation failed!\n");
return 1;
}
foo (spvar , 1, 2 );
foo (spvar , 3, 4);
foo (spvar , 3, 4);
free(spvar); // Free the memory
return 0;
}