簡體   English   中英

從函數中傳遞結構數組

[英]Passing array of structs from function

對C來說很新,我想弄清楚(對於一項任務)如何正確使用結構和函數。 具體來說,我無法確定如何從函數傳遞結構數組。

該函數應該從文件中獲取數據並輸入到數組中。 輸入文件包含以下數據:1 Al 2 Bill 3 Clark 4 Dean 5 Ellen

在我調用函數之后,我希望能夠在main函數中查看數組值。

我不認為我正確地傳遞了結構但不確定我哪里出錯了。 有什么建議么? 謝謝。

這是我的代碼嘗試:

// 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

你必須記住數組衰減到指針,所以在loadName函數中,變量N實際上是一個指針,其行為與任何其他局部變量一樣。 這意味着如果你重新分配它,你只需重新分配指針的本地副本。 這是第一件事。

第二件事是你傳入一個指向已經分配的內存的指針,一個包含五個結構的數組。 無需在函數內部再次分配。

這導致我第三件事,你在循環的每次迭代中分配,從而失去先前的分配和泄漏內存。

你應該注意,因為你傳遞的數組只為五個結構分配了空間,如果你試圖讀取超過數組限制的數據,並且會有一個緩沖區溢出導致所謂的未定義行為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM