简体   繁体   中英

Updating struct array fails in C

I'm looking for a simple solution to this. I only have one element and could easily turn it into a simple array of long integers but in the future I will have a struct of random data types so instead of me declaring a bunch of separate arrays of random types, I want to pack the data into a struct.

In this code the problem lies with the calling of load() but I don't know how to solve it. When I use the & , in front of the struct variable, the compiler reports warning: passing argument 1 of 'load' from incompatible pointer type .

The output I expect instead of errors or a segmentation fault is:

0= 1
1= 11

What am I doing wrong?

and here's the code:

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

typedef struct{
    long n;
}a;

void load(a** x){
    x[0]->n=1;
    x[1]->n=11;
}

int main(void){
    a** b=malloc(200);
    b[0]->n=2;
    b[1]->n=2;
    load(&b); //trouble starts here
    printf("0= %ld\n",b[0]->n);
    printf("1= %ld\n",b[1]->n);
    free(b);
    return 0;
}

You don't need pointer to pointers. Just use

a* b=malloc(ELEMENTS * sizeof (a)); // essentially array with nr of ELEMENTS of type a

The function

void load(a* x){
    x[0].n=1; // 0th structure object
    x[1].n=11; // 1th structure object .. you can access till ELEMENT-th index
}

You can call it like

load(b);  // you can directly pass the pointer

Anytime you run malloc , you need to check that it has not returned a NULL pointer (ptr == 0). If you try and access a NULL pointer, it can throw a segmentation fault.

One way to do this would be...

a** b=malloc(200);
if(b != 0)
{
   //The rest of the code.
}

Thanks for the help, but I couldn't accept one answer because everyone solved portions of the problem.

Here's what I came up with:

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

typedef struct{
    long n;
}a;

void load(a* x){
    x[0].n=1;
    x[1].n=11;
}

int main(void){
    a* b=calloc(1,sizeof(a)*100);
    if (!b){printf("memory error\n");return 1;}
    b[0].n=2;
    b[1].n=2;
    load(b);
    printf("0= %ld\n",b[0].n);
    printf("1= %ld\n",b[1].n);
    free(b);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM