I have an unnamed structure called `FooStruct', and I wrote a function for it that initializes all its variables and also takes care of dynamic memory allocation.
I tried running this code, but it is not producing the results that I am expecting. For some reason, the variables are initialized correctly when inside the function, but then they change again once the block is exited.
A project that I'm working on requires that I use unnamed structs only. Why is this happening?
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int fooPrimitive;
} FooStruct;
void FooStructInit(FooStruct * ptr, int num) {
ptr = (FooStruct*)malloc(sizeof(FooStruct));
ptr -> fooPrimitive = num;
// Expected output: 5
// Actual output: 5
printf("ptr -> fooPrimitive: %d\n", (ptr -> fooPrimitive));
}
int main() {
FooStruct * ptr;
FooStructInit(ptr, 5);
// Expected output: 5
// Actual output: some random number
printf("FooStruct -> fooPrimitive: %d\n", (ptr -> fooPrimitive));
}