c - working with pointers struct automatically updated -
i have product sales management program have structure storing product data, store customer data , store sales data. when insert new sale has associated existing product serial number , id of existing customer. how guarantee when data products , customers struct changed sales struct updated?
here's have:
typedef struct{ char serialnumber[10] char description[100] float price }stproducts; typedef struct{ int id; char name[50] char adress[100] int phonenumber }stcustomers; typedef struct{ int idcustomersale; char serialnumberproductsale[10] float endprice; }stsales; int main() { stproducts pr[1000]; int countproducts =0; stcustomers cust[500]; int countcustomers=0; stsales sal[1000]; int countsales=0; }
part of function insert sale:
void insertsale(stsales sal[], int *countsales, stproduct pr[], int countproduct,stcustomers cust[], int countcustomers) { char psale[10]; int number; consultproducts(pr, countproducts); consultcustomers(cust,countcustomers); printf("insert product serial number of sale:"); fgets(psale, sizeof psale, stdin); strcpy(sal[*countsales].serialnumberproductsale,psale); printf("insert customer id of sale:"); scanf ("%d", &number); sal[*countsales].idcustomersale=number; //.................... }
for example let's imagine id field changed on customer struct, automatically customer id associated sale (idcustomersale) must updated.
the answer quite simple , fundamental principle independent of language use: avoid repeating/copying information around.
make sale
refer other objects (i.e. product , customer). you'd in relational db, using foreign keys.
assuming each sale made of single product:
typedef struct { stcustomers* customer; stproducts* product; } stsales;
so, let's sales kept in static array
of sales instances, have done
unsigned int n=0; // count of sales reached @ point in time stsales sal[maxsales]; stsales *p; ... p = &sal[n++];
or of pointers , allocated on demand
stsales *sal[maxsales]; p = malloc(sizeof(stsales)); // no error checking, demo! sal[n++] = p;
in both cases can access fields had copied on (and other field) with
p->customer->id; p->product->serialnumber;
i recommend manage data structures (for sales , other objects) via dynamic memory allocation.
so, assuming sal
, n
global variables (i.e. declared outside main
, not design practice, now), insertsale
function become
stsales *insertsale(stcustomers* customer, stproducts* product) { p = malloc(sizeof(stsales)); // no error checking, demo! if (p != null) { sal[n++] = p; p->customer = customer; p->product = product; } return(p); }
of course, sales instances should freed if/when deleted. leave exercise find out how you. :)
Comments
Post a Comment