Tyler Treat
Tyler Treat

Reputation: 14998

Accessing and setting array values within structs

I have a struct like this:

typedef struct {
    int sizes[3];
    float **vals[3]; // an array of size 3 of float ** pointers
} mystruct;

What I'm trying to do is set these array values in a function that takes a pointer to a mystruct.

void populateStruct(mystruct *s) {
    int i, j, n;

    for (n = 0; n < 3; n++) {
        scanf("%d", &s->sizes[n]);

        // Malloc the float pointers (**vals) based on the scanned sizes
        s->vals[n] = (float **)malloc(s->sizes[n] * sizeof(float *));
        for (i = 0; i < s->sizes[n]; i++)
            s->vals[n][i] = (float *)malloc(s->sizes[n] * sizeof(float));

        // Populate the float "arrays"
        for (i = 0; i < s->sizes[n]; i++) {
            for (j = 0; j < s->sizes[n]; j++) {
                scanf("%f", &s->vals[n][i][j]);
            }
        }
    }
}

Here is how I'm using the function in main:

int main() {
    mystruct *s1;
    populateStructure(s1);
    return 0;
}

This code compiles fine, but I get a seg fault when I run it. C is not a strong point of mine, so I'm not too sure what I'm doing wrong.

Upvotes: 1

Views: 2041

Answers (2)

tristan
tristan

Reputation: 4322

mystruct *s1; 

s1 is only a pointer with unpredictable value. You didn't allocate memory for the struct you need. Dereferencing a wild (uninitialized) pointer would cause segv. You can modify your code to either:

    mystruct s1;
    populateStructure(&s1);

or

    mystruct *s1 = (mystruct *)malloc(sizeof(mystruct));
    populateStructure(s1);

( don't forget to free s1 in the second one)

Upvotes: 1

Asterisk
Asterisk

Reputation: 3574

How are you declaring your s structure and how are you passing it?

In your function where you call populateStruct you should probably declare s:

as mystruct s and call populateStruct(&s)

or

mystruct *s;
s = malloc(sizeof(mystruct));
populateStruct(s);

Upvotes: 1

Related Questions