Okay, i have tried all solutions suggested but still no joy. The code I have so far is
`struct account* accounts = (struct account*)malloc(sizeof(struct account));
while (1) {
printf(" 1. New Account\n 2. Close Account\n 3. Access Account\n 4. quit\n");
int choice = 0;
scanf("%d", &choice);
int numberAccounts = 0;
switch(choice){
case 1:
accounts = realloc(accounts, sizeof(struct account) * (numberAccounts + 2));
newAccount(accounts , sizeof *accounts, numberAccounts);
numberAccounts++;
break;
case 2:
printf("first name = %s\n", accounts[0].firstName);
printf("first name = %s\n", accounts[1].firstName);
break;
case 4: exit(1);
}
void newAccount(struct account *accounts , int size , int numberAccounts) {
printf("please enter first name\n");
scanf("%s", accounts[numberAccounts].firstName);
printf("please enter last name\n");
scanf("%s", accounts[numberAccounts].lastName);
printf("please enter overdraft\n");
scanf("%d", &accounts[numberAccounts].overdraft);
accounts[numberAccounts].accountNumber = (100 + numberAccounts);
accounts[numberAccounts].balance = 0.0;
}
It still spits out garbage for accounts[1]. However I did do a stripped down version, same code, but with less crap and that works fine. I dont understand it. its the same.
struct account{
char *firstName;
};
int main(int argc, char** argv) {
struct account* accounts = (struct account*)malloc(sizeof(struct account));
accounts[0].firstName = "ben";
accounts = realloc(accounts, sizeof(struct account) * 2);
accounts[1].firstName = "tori";
printf("accounts[0] = %s\n", accounts[0].firstName);
printf("accounts[1] = %s\n", accounts[1].firstName);
The output from the first code is
first name = tori first name = lication\debug
and the second
first name = ben first name = tori as it should be. inputs were ben first, tori second for 2 accounts. weird
`