I have a problem with structure arrays, to insert dynamic values.
Cannot insert values into dynamic arrays, response "Exited, segmentation fault".
Can anyone help me, that's problem. Thank you ............................................................................................................................................................................................................................................................................................................................
Syntax:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define FLUSH while (getchar() != '\n')
typedef struct{
char *Name;
int Qty;
} Item;
static void insert(Item* i, char *name, int qty)
{
i->Name = name;
i->Qty = qty;
}
int main() {
int storage = 0, menu;
printf("Temporary Storage\n");
//Input storage amount
bool isInputStorage = true;
while (isInputStorage) {
printf("Input Storage amount [1..10]: ");
scanf("%d", &storage);
if (storage <= 10 && storage >= 1) {
isInputStorage = false;
}
else {
printf("\n[!]Please enter numbers [1..10] for Storage amount.\n\n");
}
FLUSH;
}
Item *dataItems;
//Input Menu
bool isInputMenu = true;
while (isInputMenu) {
printf("\n\nMenu\n");
printf("=============\n");
printf("1. Add items\n");
printf("4. Exit\n");
printf("Choose Menu [1..4]: ");
scanf("%d", &menu);
if (menu >= 1 && menu <= 4) {
if (menu == 1) {
char* name;
int qty;
//Insert to arrays storage
int currentStorageAmount = sizeof(dataItems) / sizeof(dataItems[0]);
if (currentStorageAmount >= storage) {
printf("Storage is Full");
}
else {
printf("Input name of Item : ");
scanf("%s", name);
bool isQty = true;
while (isQty) {
FLUSH;
printf("Input qty of Item : ");
int correctQty = scanf("%d", &qty);
if (correctQty == 1) {
isQty = false;
}
else {
printf("\n[!]Please enter number for Qty!\n\n");
}
}
//action to insert
insert(&dataItems[currentStorageAmount], name, qty);
}
}
else if (menu == 4) {
printf("\nThank you for using this application.\n");
isInputMenu = false;
}
}
else {
printf("\n[!]Please enter numbers [1..4] for choose Menu.");
}
menu = 0;
FLUSH;
}
system("pause");
return 0;
}
Result:
Temporary Storage
Input Storage amount [1..10]: 4
Menu
=============
1. Add items
4. Exit
Choose Menu [1..4]: 1
Input name of Item : test
Input qty of Item : 5
exited, segmentation fault
dataItemsis not initialized to any memory location and could be located anywhere in memory, allocate the "dynamic array", either usingItem dataItems[storage]orItem *dataItems = malloc(sizeof(Item) * storage)and checkdataItembefore using.char* name;...scanf("%s", name);because you haven't created any memory for the name to go - in fact you haven't initialized the pointer to ANYTHING. It's the same problem that @dvhh mentioned. Basically you need to initialize ALL your variables.