I'm trying to modify elements of an array in a function. This works fine when kept in main but when I port it to a function it segfaults after accessing the first member of the array.
The code below is just a reduced version of my actual code to show where I'm getting the segfault.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned short id;
} voter;
void initialise(voter** votersPtr, unsigned short *numOfVoters) {
*votersPtr = malloc(sizeof(voter)*(*numOfVoters));
for(int i = 0; i < *numOfVoters; i++) {
votersPtr[i]->id = (unsigned short) i;
printf("%hu \n", votersPtr[i]->id);
}
}
int main(void) {
unsigned short numOfVoters = 480;
voter* voters = NULL;
initialise(&voters, &numOfVoters);
return EXIT_SUCCESS;
}
Any help would be greatly appreciated, thank you.
initialisefunction start withvoter *ptr = malloc..., and then at the end, do*votersPtr = ptr;. IMHO this makes the code easier to read, and also means that if you have to abort the function for some reason part-way through constructing the result, you don't end up with the caller seeing partially-constructed result.