0
对C很新颖,我试图弄清楚(对于任务)如何正确使用结构和函数。 特别是,我遇到了麻烦,如何从函数传递结构数组。传递函数结构数组
函数应该从文件中获取数据并将其输入到数组中。输入文件具有以下数据:的Al 比尔克拉克迪安埃伦
我调用该函数后,我想是能够在查看的数组值主要功能。
我不认为我正确地传递了结构,但不知道我要出错的地方。 有什么建议吗?谢谢。
这里是我的代码的尝试:
// Input file into array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int number;
char name[30];
} Name;
#define SIZE 5
// function prototypes
int loadName(char *file, Name N[]);
// function main begins program execution
int main(void)
{
char file[ 30 ]; // file name
Name N[ SIZE ]; // array to store names
size_t i, j=0; // counter
// check read function opens file correctly
if (-1 == (i = loadName (file, N))) {
puts("Employee file could not be opened");
} // end load if
printf("\n\nCheck for names in main function\n\n");
for (j=0; j<i; ++j) {
printf("%8d%18s\n", N[j].number, N[j].name);
}
return 0;
free(N);
}
// load values from name file
int loadName(char *file, Name N[])
{
FILE *inPtr; // inPtr = input file pointer
size_t i = 0; // counter
// fopen opens file. Exit program and return -1 if unable to open file
if ((inPtr = fopen("name.txt", "r")) == NULL) {
return -1;
} // end if
else {
printf("Employee Number Employee Name\n");
// read name from file
do {
N = (Name*)malloc(100);
fscanf(inPtr, "%d%s", &N[i].number, &N[i].name);
printf("%8d%18s\n", N[i].number, N[i].name);
i++;
} while (!feof(inPtr));
} // end else
fclose(inPtr); // fclose closes the file
return i; // return i after successful for loop
} // end function loadname