I'm trying to fill a structure field from a function to which the structure is given by pointer.
After allocating the structure with malloc the returned pointer is non null and the structure field is well initialized, however after returning to main. The pointer I passed to the function is null.
Here a simplified example
#include <stdlib.h>
#include <stdio.h>
#define INFO(fmt, args...) printf(fmt, ## args);
#define ERROR(fmt, args...) printf("In %s : " fmt, __func__, ## args);
typedef enum
{
ERR_OK = 0,
ERR_KO = -1,
ERR_MALLOC_FAIL = -2,
}error_t;
typedef struct
{
unsigned int field;
}test_struct;
int struct_constructor(test_struct* myStruct, unsigned int field)
{
myStruct = malloc(sizeof(test_struct));
if(NULL == myStruct)
{
ERROR("Error allocating memory for myStruct\n");
return ERR_MALLOC_FAIL;
}
INFO("passed field = %d\n", field);
myStruct->field = field;
INFO("struct field = %d\n", myStruct->field);
return ERR_OK;
}
int main(void)
{
test_struct* myStruct = NULL;
struct_constructor(myStruct, 1);
if(myStruct == NULL)
{
INFO("NULL structure in main\n");
}
}
And here is the output :
passed field = 1
struct field = 1
NULL structure in main
I don't understand why the structure's pointer is not null inside the function and is null in main.
Also I don't want to return the pointer as I'm using return code to check what's going wrong in my functions.