Home > Back-end >  How to fill an array of structs when parameter argument is a double pointer
How to fill an array of structs when parameter argument is a double pointer

Time:02-12

Working on a piece of homework, having issue with filling in a struct array with values as I keep getting a "Invalid write of size 8" error after I fill anything past the first element.

#include <stdio.h>
#include <stdlib.h>

struct DS_t {
    int a;
    double b;
    char c;
};

void f4(struct DS_t ** x) {
    *x = (struct DS_t *) malloc(4 * sizeof(struct DS_t));
    struct DS_t d1 = {3, 2.3};
    *x[0] = d1;
    *x[1] = d1;
}

int main() {
    struct DS_t * ds4_p;
    f4( &ds4_p );
    printf("DS_t[0] = {%d, %f, %s}\n", ds4_p[0].a, ds4_p[0].b, ds4_p[0].c);
    printf("DS_t[1] = {%d, %f, %s}\n", ds4_p[1].a, ds4_p[1].b, ds4_p[1].c);
    printf("DS_t[2] = {%d, %f, %s}\n", ds4_p[2].a, ds4_p[2].b, ds4_p[2].c);
    //etc
}

I want to create an array of struct DS_t using the *x to the **x in the function parameter and then fill up that array, which I believe *x = (struct DS_t *)calloc(4, sizeof(struct DS_t)); does. Seeing it through a visualizer, I see that in f4, the x points to ds4_p and then ds4_p points to 4 struct DS_t, which is what I want.

But whenever I go to try and fill it, I get that invalid write of size 8 error. I have no problem with *x[0]= d1, it fills the first element just fine, anything after is where my issue lies.

What is it that I am missing with this? Been working on it for a while and haven't had any luck with it. Maybe I'm going about it the wrong way? Just need to print out each element of the array pointer. The struct and function was all created specifically like this, so can't change any of that.

CodePudding user response:

A number of problems in the code:

  1. [] has higher order of precedence than *. So *x[0] = d1; is actually equivalent to *(x[0]) = d1;. Which is not what you want. Instead, it should be (*x)[0] = d1;. Same for the line after it of course.
  2. You are using malloc rather than calloc as you claim. Which means ds4_p[2] (and ds4_p[3]) are uninitalised. Either use calloc or don't attempt to access ds4_p[2].
  3. %s is for strings. But you only have a single char. Use %c instead. But note that d1.c is set to 0 so %c will not print any visible character.
  • Related