在链表中动态存储数据的问题
我正在尝试编写一个程序,该程序最多读取 8 个银行帐户信息并将它们动态存储在链接列表中。我编写了一个函数来计算所有输入银行账户余额的平均值,但是当我尝试调用该函数时,没有产生任何输出。你能帮我找出问题所在吗?
#include <stdio.h>
#include <stdlib.h>
//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;
//int for division of total to find the average
static int t;
//adding accounts function
account * addaccount(account * temp) {
fflush(stdin);
printf("Enter the account name: \n");
gets(temp -> name);
printf("Enter the account number: \n");
scanf("%d", & temp -> no);
printf("Enter the account balance: \n");
scanf("%f", & temp -> total);
t++; // used for finding the average
return temp;
}
// function for calculating the average
float sum(account * temp) {
float average = 1.0, sum = 0.0;
int i;
account * start;
temp = start;
for (i = 0; i < t; i++) {
sum += temp -> total;
temp = temp -> nextptr;
}
average = sum / t;
return average;
}
int main() {
int selection;
account * start = NULL;
account * save, * temp;
account * ptr;
ptr = (account * ) malloc(sizeof(account) * 8);
do {
//Menu
printf("\n1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", & selection);
switch (selection) {
case 1: {
if (ptr == NULL)
ptr = (account * ) realloc(ptr, sizeof(account));
save = addaccount(ptr);
if (start == NULL) {
start = save;
start -> nextptr = NULL;
} else {
temp = start;
while (temp -> nextptr != NULL)
temp = temp -> nextptr;
temp -> nextptr = save;
save -> nextptr = NULL;
}
break;
}
case 2: {
float avg;
avg = sum(temp);
printf("%f", avg);
break;
}
case 3: {
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
break;
}
}
} while (selection != 4);
return 0;
}