0

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;
}
Mike -- No longer here
  • 2,064
  • 1
  • 15
  • 37
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Oct 15 '15 at 18:05

3 Answers3

2

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
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

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.
}
CodeMouse92
  • 6,840
  • 14
  • 73
  • 130
  • That is easy to catch but I just found out my segmentation fault happens when `b[0]->n=2;` is executed if I change `load(&b)` to `load(b)` – Mike -- No longer here Oct 15 '15 at 18:07
  • If b is a pointer to a pointer of `a` (what IS `a`), then you're getting some funky pointer arithmetic off of that, which is one more way to segfault. @Giorgi is absolutely right in his answer. – CodeMouse92 Oct 15 '15 at 18:09
0

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;
}
Mike -- No longer here
  • 2,064
  • 1
  • 15
  • 37