peter man
peter man

Reputation: 3

segmentation fault while trying to write to element of struct array

#include <stdio.h>
#include <stdlib.h>
struct item{
    int man;
};
int writeto(struct item **itens, int n){
    *itens = malloc(sizeof(struct item)*n);
    for (int i = 0; i < n; i++){
        itens[i]->man = i*2;
    }

}
int main(){
    struct item* itens;
    writeto(&itens,2);
    printf("%d\n",itens[0] );
    printf("%d\n",itens[1] );
    return 0;
}

Hello. I create an array of struct itens and then allocate memory for that array inside the function and fill it. the first element works ([0]) and I can access it outside the function, however, the second never works. What am I doing wrong? Thanks

Upvotes: 0

Views: 44

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15566

You're accessing itens wrong here:

itens[i]->man = i*2;

itens is a pointer to an array of struct item. Instead, do this:

(*itens)[i].man = i*2;

Also, you're printing wrong, too.

Instead of:

printf("%d\n",itens[0] );
printf("%d\n",itens[1] );

use:

printf("%d\n", itens[0].man);
printf("%d\n", itens[1].man);

Upvotes: 4

Related Questions