2

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.

1
  • 1
    One way to avoid this sort of error is to make the initialise function start with voter *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. Commented Nov 24, 2015 at 21:38

3 Answers 3

2

votersPtr[i]->id, which is the same as (*votersPtr[i]).id should be (*votersPtr)[i].id.

Sign up to request clarification or add additional context in comments.

Comments

0

The type voter ** is ambiguously either a pointer to an array of pointers to voter objects or a pointer to a pointer to an array of voter objects. Your code is using it as the first, but should be using it as the second. Change

votersPtr[i]->id = ...

to

(*votersPtr)[i].id = ...

and everything should work.

1 Comment

Thank you for the explanation as to why I can't use "->", I understand the issue now.
0

Remember that votersPtr is a pointer to a pointer of an array.

So shouldn't the following line:

votersPtr[i]->id = (unsigned short) i;

Instead be:

(*votersPtr)[i].id = (unsigned short) i;

1 Comment

Thank you! I had actually tried this and forgot to change it in the printf statement causing the segfault to still occur.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.