I've been trying for hours to get this function to work correctly. Here's the assignment:
Add: Request the part name, price, and quantity. Save the information to a dynamically allocated array of structs. You may allocate space for up to 3 structs at a time. You will need to create more memory dynamically as needed. Use this struct (you may use typedef if you want to):
So far the code I have is
typedef struct {
char* name;
float price;
int quantity;
}part;
void add(part *item, int *part_count)
{
//char temp[100];
if (!item){
item = malloc(sizeof(part)*3);
}
else{
item = realloc(item, sizeof(part) * ((*part_count*3) + 1));
}
item[*part_count].name = malloc(sizeof(char)*64); // max of 64 characters
printf("Please enter item name: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%s", item[*part_count].name);
scanf("%64s", item[*part_count].name);
printf("Please enter item price: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%f", &item[*part_count].price);
scanf("%f", &item[*part_count].price);
printf("Please enter item quantity: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%d", &item[*part_count].quantity);
scanf("%d", &item[*part_count].quantity);
*part_count = *part_count+ 1;
}
I had attempted to take the input with fgets()
and sscanf()
but using that code it never allows the user to input data and then ends the function.
I believe the problem resides with my allocation of memory as I am getting segmentation faults when I try to do anything with the array such as print out the contents.
part_count
? If it's the number of elements, you can't access that element. So if your array is of size10
, you can't accessarray[10]
.