-2

I am using the following code and in line "arr[0]->p = (int *)malloc(m * sizeof(int));"I have "Segmentation fault (core dumped)". I need to write my code in this way...

Can someone help how can I write this and why my code have this error?

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

typedef struct data{
    int *p;
}data;

void main(){
    int n = 10, 
        m = 5 ;
        
    data **arr = (data**)malloc(n * sizeof(struct data*));
    arr[0]->p = (int *)malloc(m * sizeof(int));

}

something like this it works

    /************************************************************
    *                                                           *
    *      data *arr = (data*)malloc(sizeof(struct data));      *
    *      arr->p = (int *)malloc(m * sizeof(int));             *
    *                                                           *
    *************************************************************/
TheFish
  • 3
  • 2
  • 1
    Well, segmentation fault definitely means that your program is trying to write data somewhere it's not allowed to, possibly it's trying to overwrite memory allocated by the Operating System to something else. – Ridwan Jan 05 '21 at 07:59
  • You allocated memory for `arr`, but never allocated memory for `arr[0]`. – Barmar Jan 05 '21 at 08:05
  • [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Jan 05 '21 at 08:10

1 Answers1

1

You don't need an array of pointers. Allocate an array of structs and then allocate memory for the p member of the structs.

data *arr = malloc(n * sizeof(data));
for (int i = 0; i < n; i++) {
    arr[i].p = malloc(m * sizeof(int));
}

If you really do need an array of pointers, you need to allocate memory for the struct that each pointer points to.

data **arr = malloc(n * sizeof(data*));
for (int i = 0; i < n; i++) {
    arr[i] = malloc(sizeof(struct data));
    arr[i]->p = malloc(m * sizeof(int));
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Nice, that was my mistake with "arr[0] = (data*)malloc(sizeof(struct data));" it work fine. Thank you – TheFish Jan 05 '21 at 08:11