使用来自结构的指针(成员)的动态内存分配中的分段错误(核心转储)
Segmentation fault (core dumped) in dynamic memory allocation using a pointer(member) from struct
我正在使用以下代码并在行“arr[0]->p = (int *)malloc(m * sizeof(int));”中出现“分段错误(核心已转储)”。
我需要这样写我的代码...
谁能帮我写这个,为什么我的代码有这个错误?
#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));
}
像这样的东西行得通
/************************************************************
* *
* data *arr = (data*)malloc(sizeof(struct data)); *
* arr->p = (int *)malloc(m * sizeof(int)); *
* *
*************************************************************/
您不需要指针数组。分配一个结构数组,然后为结构的 p
成员分配内存。
data *arr = malloc(n * sizeof(data));
for (int i = 0; i < n; i++) {
arr[i].p = malloc(m * sizeof(int));
}
如果确实需要一个指针数组,则需要为每个指针指向的结构分配内存。
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));
}
我正在使用以下代码并在行“arr[0]->p = (int *)malloc(m * sizeof(int));”中出现“分段错误(核心已转储)”。 我需要这样写我的代码...
谁能帮我写这个,为什么我的代码有这个错误?
#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));
}
像这样的东西行得通
/************************************************************
* *
* data *arr = (data*)malloc(sizeof(struct data)); *
* arr->p = (int *)malloc(m * sizeof(int)); *
* *
*************************************************************/
您不需要指针数组。分配一个结构数组,然后为结构的 p
成员分配内存。
data *arr = malloc(n * sizeof(data));
for (int i = 0; i < n; i++) {
arr[i].p = malloc(m * sizeof(int));
}
如果确实需要一个指针数组,则需要为每个指针指向的结构分配内存。
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));
}