I am trying to allocate an array of structs within a function.
My struct is as follows:
typedef struct{
uint16_t taskNumber;
uint16_t taskType;
double lat;
double lon;
double speed;
uint8_t successCriteria;
uint16_t successValue;
uint8_t nextPoint;
}missionPoint;
In my code I declare a missionPoint-pointer which I then pass into the function that will dynamically allocate it after parsing a file and figuring out how big it needs to be.
Currently this is how my code looks:
missionPoint* mission; //declaring the pointer
parseMission(mission);
The parseMission function will then parse a specific file and find out how many missionPoints I need and will then allocate it in the following manner:
mission = (missionPoint*) malloc(n * sizeof(missionPoint));
where n is the parsed number of missionPoints I need.
The problem is that within the function I can see the proper values but not outside of it; once the function returns it’s like nothing happened.
I would appreciate your help in making it so that the function modifies the original pointer and I can see the data from outside the function.
You need to pass a reference to the pointer, i.e. a double pointer, because the address itself is going to be modified:
The argument of
parseMissionshould now be of typemissionPoint **instead ofmissionPoint *:This wouldn’t be necessary if you only wanted to modify the memory
missionis pointing to, but it cannot be avoided since you are assigning a new value to the pointer itself.Also note that casting the return value of
mallocis not necessary in C.