Im trying to create a dynamic database where I can modify its size.
This is the code that I have written so far where I assign the product char pointer to null and price to -1
What I would expect for it is to have created the data base and let me keep creating new ones with new sizes which replace the old database but so far it only returns a memory direction and stops the program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _product_t {
char *product;
float price;
} product_t;
product_t *newDatabase(product_t *database, int *dbSize, int newSize) {
free(database);
product_t *newdatabase = (product_t*)malloc(sizeof(database)*newSize);
newdatabase->product = (char*)malloc(sizeof(char)*20);
newdatabase->product = NULL;
newdatabase->price = -1;
free(newdatabase->product);
return newdatabase;
}
int main(void) {
product_t *database = NULL;
int dbSize = 0;
char cmd;
do{
printf("Command?");
scanf(" %c", &cmd);
switch (cmd) {
case 'q':
printf("Bye!");
break;
case 'n':
printf("Size? ");
int newSize2 = 0;
scanf("%d", newSize2);
newDatabase(database, &dbSize, newSize2);
break;
default:
printf("Unkown command '%c'\n",cmd);
}
}while(cmd != 'q');
return 0;
}
Use
realloc()to change the size of an allocation. The size of the array should usesizeof(*database), sincesizeof(database)is just the size of a pointer, not the size of the structure.When initializing the new array elements, you need a loop.
newdatabasepoints to the beginning of the array, not the new elements that were added.You also need to fix the line that asks for the size:
Except when reading a string, you need to pass the address of the variable to write into, so it should be: