【发布时间】:2014-03-03 17:14:15
【问题描述】:
对 C 非常陌生,我正在尝试弄清楚(对于分配)如何正确使用结构和函数。 具体来说,我无法弄清楚如何从函数中传递结构数组。
该函数应该从文件中获取数据并输入到数组中。输入文件有以下数据: 1 铝 2 账单 3 克拉克 4 院长 5 艾伦
调用函数后,我希望能够在主函数中查看数组值。
我认为我没有正确传递结构,但不确定我哪里出错了。 有什么建议么?谢谢。
这是我的代码尝试:
// 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
【问题讨论】: