[英]Assign values from struct to array in C
如何将结构的先前读取的元素分配给一个空(新)数组?
在以下示例中,在struct2
每个输入元素struct2
,应将其存储到新数组arr
。
此示例给出了SIGSEGV分段错误。
有人可以指出如何解决这个问题吗?
编辑:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char name[30];
float price;
}PRODUCT;
typedef struct
{
int prodNumRep;
PRODUCT *productsRep;
float *quantityRep;
}REPOSITORY;
void inputProd(PRODUCT *prod)
{
printf("ID: ");
scanf("%d",&prod->id);
printf("Name: ");
scanf("%s",prod->name);
printf("Price: ");
scanf("%f",&prod->price);
}
void inputRep(REPOSITORY *rep)
{
printf("REPOSITORY: \n");
printf("Number of products: ");
scanf("%d",&rep->prodNumRep);
rep->productsRep=calloc(rep->prodNumRep,sizeof(*rep->productsRep));
rep->quantityRep=malloc(rep->prodNumRep*sizeof(float));
//new array
REPOSITORY *arr;
arr=(REPOSITORY*)malloc(rep->prodNumRep * sizeof(REPOSITORY));
int i;
for(i=0;i<rep->prodNumRep;i++)
{
printf("%d. product: \n",i+1);
inputProd(rep->productsRep+i);
printf("Quantity: ");
scanf("%f",&rep->quantityRep[i]);
//assign struct2 (previously read with inputStruct1) to array - SIGSEGV segmentation fault
arr->productsRep[i]=rep->productsRep[i];
arr->quantityRep[i]=rep->quantityRep[i];
}
}
int main()
{
REPOSITORY *rep;
rep=(REPOSITORY *)malloc(sizeof(REPOSITORY));
inputRep(rep);
return 0;
}
您的问题是arr->productsRep[i]
实际上正在尝试取消对productsRep的指针的引用,但是您尚未为arr->productsRep[i]
分配任何内存。 我知道您正在尝试执行的操作,但是我认为您需要重组逻辑和执行流程。
无需在函数中声明新数组。 从函数中删除以下语句
//new array
REPOSITORY *arr;
arr=(REPOSITORY*)malloc(rep->prodNumRep * sizeof(REPOSITORY));
和
//assign struct2 (previously read with inputStruct1) to array - SIGSEGV segmentation fault
arr->productsRep[i]=rep->productsRep[i];
arr->quantityRep[i]=rep->quantityRep[i];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.