簡體   English   中英

C,為結構數組內的字符串分配內存

[英]C, allocating memory for strings inside array of structs

我已經在此站點上對該問題進行了足夠的研究,但仍未找到解決方案。 我有一個結構數組,我想從文件中讀取一些記錄並將它們存儲在結構中。 問題是內存的分配。 這是我使用的結構:

struct Rec{
    int mat;
    char *nome;
    char *cognome;
};
typedef struct Rec* Record; 

這是readFromFile函數:

void readFromFile(char* fileName, Record** data, int* pn) 
{
   char line[LINE_LENGTH];
   int n, i;
   char* token;
   printf("\n\nReading file %s\n", fileName);
   FILE* fin = fopen(fileName, "r"); 
   if (fin == NULL) 
   {  printf("Error readinf file\n");getch();
      goto end;
   }
   n = 0;         // first read to know the number of lines
   while (fgets(line, LINE_LENGTH, fin) != NULL) n++;
   n = (n < MAX_LENGTH ? n : MAX_LENGTH);
   printf("N: %d\n", n);
   *pn = n;

   //Then I allocate the memory for the n lines I previously read
   *data = (Record*)malloc(n * sizeof(Record));
   if(*data == NULL){
    printf("Problem allocating memory\n");
    exit(0);
   }
   i = 0;
   for(i = 0; i < n; i++){
        (*data)[i].nome = malloc(sizeof(char) * MAX_LENGTH + 1);
        if((*data)[i]->nome == NULL){
            printf("Problem allocating memory\n");
            exit(1);
        }
        //Here comes the problem, the allocation of the second string fails and the program exit
        (*data)[i]->cognome = malloc((sizeof(char) * MAX_LENGTH + 1));
        if((*data)[i]->cognome == NULL){
            printf("Problem allocating memory\n");
            exit(2);
        }
   }
   rewind(fin);                         
   n = 0;
   while (fgets(line, LINE_LENGTH, fin) != NULL && n < MAX_LENGTH)
   {
        token = strtok(line, ";");
        strcpy((*data)[n]->nome, token);
        token = strtok(line, ";");
        strcpy((*data)[n]->cognome, token);
        token = strtok(line, ";");
        (*data)[n]->mat = atoi(token);
        n++;

   }
   fclose(fin);                         
   end:return;
}

我試圖以多種方式修改結構和代碼,但沒有找到解決方案,我認為這可能是指針問題,但我無法弄清楚。 readFromFile函數是由教授提供的,旨在從文件中讀取int,我不得不對其進行修改以讀取記錄。

Record定義為

typedef struct Rec* Record;

因此,它是指向結構Rec。的指針。 malloc返回指向已分配內存的指針(或NULL ),但是將其強制轉換為指針的指針

*data = (Record*)malloc(n * sizeof(Record));
//    =  Rec**

之間有很大的區別:

(*data)[i].nome = malloc(sizeof(char) * MAX_LENGTH + 1);

和:

(*data)[i]->cognome = malloc((sizeof(char) * MAX_LENGTH + 1));

使用帶點符號的第一行表示對struct成員的訪問,而->表示使用指針表示即struct指針訪問struct的成員。

那里顯示出混亂,因為(*data)是指向Record類型的結構的指針,該結構是Rec的類型定義。

typedef struct Rec* Record; 

由於剝離后的dataRecord類型定義,因此別名為Rec struct指針。 在確定輸入數據集中的行數后,將作為參數一部分的雙指針聲明為指針數組:

*data = (Record*)malloc(n * sizeof(Record));

對於數組中的每個條目,訪問成員數據將是:

(*data)[i] dot name_of_member

如果類型定義如下,則該規則將已更改:

typedef struct Rec Record;

即正常的結構,沒有使用指針。

如果分配成功, 那么就可以訪問成員數據了,

(*data)[i]->name_of_member

但是, 不要嘗試將指針隱藏在typedef后面,因為這會使您感到悲傷,以后再返回代碼,並想知道為什么它失敗了,所以隱藏的指針已經咬住了您!

暫無
暫無

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

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