C语言 如何从struct中对数组进行malloc



我有一个摘要,应该有一个数组,其大小我还不知道在main我尝试。例如,在这里,我创建了一个定义N,但实际上,我以不同的方式接受不同的数据,包括数组W。我必须为我的数组arr结构分配内存。

#include <stdio.h>
#include <stdlib.h>
#define N 10
struct vector {
int size;
int *arr;
int length;
};
void main(void) {  
int w[N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
struct vector *ptr;
ptr->arr = (int *)malloc(sizeof(int) * N);
if (ptr->arr == NULL) 
printf("Unable to allocate memory :(n");
for (int i = 0; i < N; i++) {
ptr->arr[i] = w[i];
printf("%d ", ptr->arr[i]);
}
printf("n");
}

尝试了不同的方法,但都不起作用。在终端中给出一个错误:Segmentation fault (core dumped).请帮帮我

您需要首先用您的结构类型分配PTR。现在,ptr=Null,在分配ptr->arr之前,您需要它指向具有结构大小的内存位置。

试试这个:

#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct vector {
int size;
int *arr;
int length;
}vector_t;
void main(void)
{  
int w[N]={1,2,3,4,5,6,7,8,9};
vector_t *ptr=(vector_t *)malloc(sizeof(vector_t));
ptr->arr=(int *) malloc( sizeof(int)*N );
/* ---- the rest of your code--- */
free(ptr->arr);
free(ptr);

}

最新更新