If a pointer is your phonebook entry, a pointer to that pointer can be thought of telling you the phonebook in which that entry exists.
Looking at your code:
struct customer {
char name[20];
char surname[20];
int code;
float money;
};
First, you should not use a float type for money.
Your question is related to C FAQ 4.8. Basically, you have a function to insert a customer record. Where do you want to insert the record? Something that holds the record obviously, a phonebook, a database etc. So, what you need is a pointer to something that holds pointers pointers to the objects you want to insert.
Now, as for the rest of your code, first, note that you should not cast the return value of malloc
. Second, using scanf
is a serious security risk. Third, you are allocating a new customer record in the inserts
function, but you have no way to communicate any failure to the code that calls your function.
Arguably, the name of the function should be something like create_customer_interactive
to convey that it does more than just insert a record in a list of records.
Here is how one might structure your code:
#include <stdio.h>
#include <stdlib.h>
struct customer {
char *name;
char *surname;
int code;
int money; /* in cents */
};
typedef struct customer *PCustomer;
int read_customer_record(FILE *fp, PCustomer customer) {
/* dummy implementation */
customer->name = "A. Tester";
customer->surname = "McDonald";
customer->code = 123;
customer->money = 100 * 100;
return 1;
}
PCustomer insert_record_interactive(PCustomer *db, FILE *fp) {
PCustomer tmp = malloc(sizeof(*tmp));
if (!tmp) {
return NULL;
}
if (!read_customer_record(fp, tmp)) {
free(tmp);
return NULL;
}
*db = tmp;
return tmp;
}
int main(void) {
PCustomer new_customer;
PCustomer *db = malloc(3 * sizeof(*db));
if (!db) {
perror("Failed to allocate room for customer records");
exit(EXIT_FAILURE);
}
/* insert a record in the second slot */
new_customer = insert_record_interactive(&db[1], stdin);
if (!new_customer) {
perror("Failed to read customer record");
exit(EXIT_FAILURE);
}
printf(
"%s %s (%d) : $%.2f\n",
new_customer->name,
new_customer->surname,
new_customer->code,
((double)new_customer->money) / 100.0
);
return 0;
}