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;
}
CodePudding user response:
Use realloc()
to change the size of an allocation. The size of the array should use sizeof(*database)
, since sizeof(database)
is just the size of a pointer, not the size of the structure.
When initializing the new array elements, you need a loop. newdatabase
points to the beginning of the array, not the new elements that were added.
product_t *newDatabase(product_t *database, &dbSize, int newSize) {
product_t *newdatabase = realloc(database, sizeof(*database)*newSize);
if (!newdatabase) {
printf("Unable to allocate memory\n");
exit(1);
}
for (int i = *dbSize; i < newSize; i ) {
newdatabase[i].product = (char*)malloc(sizeof(char)*20);
newdatabase[i].price = -1;
}
return newdatabase;
}
CodePudding user response:
Completed version that works.
#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 = realloc(database, sizeof(database)*newSize);
*dbSize = newSize;
for (int i = *dbSize; i < newSize; i ) {
newdatabase[i].product = (char*)malloc(sizeof(char)*20);
newdatabase[i].price = -1;
}
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);
database = newDatabase(database, &dbSize, newSize2);
break;
default:
printf("Unkown command '%c'\n",cmd);
}
}while(cmd != 'q');
return 0;
}