简体   繁体   中英

Segmentation fault (core dumped) in dynamic memory allocation using a pointer(member) from struct

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));             *
    *                                                           *
    *************************************************************/

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));
}

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