My program (Eclipse Neon) crashes while I run my program. I found the line with the problem, but I don't know how to solve it.
First I make a dynamic array:
int nLeden = 0;
AtletiekLid *ledenArray = (AtletiekLid *)calloc(nLeden, sizeof(AtletiekLid));
with this struct:
typedef struct {
char naam[30];
unsigned leeftijd;
} AtletiekLid;
After that I do this:
AtletiekLid lid;
strcpy(&lid.naam, "Test");
strcpy(&lid.leeftijd, "18");
addLid(ledenArray, lid, nLeden); //Program stopped working (windows error) on this line.
the addLid
function:
void addLid(AtletiekLid **ledenArray, AtletiekLid lid, int *nLeden) {
*ledenArray = (AtletiekLid *)realloc(*ledenArray, (*nLeden + 1) * sizeof(AtletiekLid));
(*ledenArray)[*nLeden] = lid;
(*nLeden)++;
}
In the addLid
(where my program crashed) it crashed on this line:
*ledenArray = (AtletiekLid *)realloc...
Can someone help me, I don't know what I'm doing wrong.
There are 3 errors in the code fragment posted:
strcpy(&lid.naam, "Test");
should read strcpy(lid.naam, "Test");
as lid.naam
is an array that decays into a pointer to its first element when passed to a function.
strcpy(&lid.leeftijd, "18");
is incorrect. lid.leeftijd
is an unsigned int
, you should instead write lid.leeftijd = 18;
addLid(ledenArray, lid, nLeden);
is incorrect too as addLid
expects a pointer to a pointer as its first argument and a pointer to the number of elements as the third, so it can update these in the caller's scope. You should write this instead: addLid(&ledenArray, lid, &nLeden);
Note that you should compile your program with more warnings enabled to let the compiler issue useful diagnostics about this kind of type mismatches.