How to assign previously read element of a struct to an empty (new) array?
In the following example, after each input element of struct2
, it should be stored to a new array arr
.
This example gives SIGSEGV segmentation fault.
Could someone point out how to resolve this?
EDIT:
#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;
}