2017-03-31 80 views
0

所以我有這個問題,我一直只得到我的主要錯誤代碼(1)結構已被定義,當我將我的結構保存在一個頭文件和(2)我正在使用不兼容的指針類型。傳遞和返回結構C

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include "functDefs.h" 
#include "writeToFile.c" 
#include "readFile.c" 
#include "inputContactInfo.c" 
#include "contactInfoStruct.h" 

int main(void) { 

    int i = 0; 
    char *ynAns; 
    struct contactId *contactInfo; 
    contactInfo = malloc(sizeof(struct contactId)); 

    do { 
      if(ynAns != NULL) { 
        free(ynAns); 
      } 
      ynAns = malloc(sizeof(char) * 5); 
      printf("\nDo you wish to enter a new contact (Yes or No)?: "); 
      fgets(ynAns, 5, stdin); 
      ynAns[(strlen(ynAns) - 1)] = '\0'; 
      if (strcmp(ynAns, "Yes") == 0) { 
        printf("\n"); 
        contactInfo = realloc(contactInfo, sizeof(struct contactId) * (i + 1)); 
        contactInfo[i] = inputContactInfo(); 
        i++; 
      } 

    } while(strcmp(ynAns, "No") != 0); 

    writeToFile(contactInfo, i); 

    readFile(i); 

    free(contactInfo); 
    return 0; 
} 

那麼這裏有我的函數定義:

void writeToFile(struct contactId *contInfo, int numContacts); 
struct contactId *inputContactInfo(); 
void readFile(int numContacts); 

這是結構的頭文件:

struct contactId { 
    char firstName[20]; 
    char lastName[20]; 
    char companyName[50]; 
    char phoneNumber[15]; 
    char email[50]; 
}; 

我得到這樣的錯誤:

IOlist.c: In function ‘main’: 
IOlist.c:28:40: error: incompatible types when assigning to  type ‘struct contactId’ from type ‘struct contactId *’ 
        contactInfo[i] = inputContactInfo(); 
            ^
IOlist.c:34:21: warning: passing argument 1 of ‘writeToFile’ from incompatible pointer type 
    writeToFile(contactInfo, i); 
       ^
In file included from IOlist.c:5:0: 
writeToFile.c:7:6: note: expected ‘struct contactId *’ but argument is of type ‘struct contactId *’ 
void writeToFile(struct contactId *contInfo, int numContacts) { 
    ^

而這些錯誤以及:

In file included from IOlist.c:5:0: 
writeToFile.c:7:6: error: conflicting types for ‘writeToFile’ 
void writeToFile(struct contactId *contInfo, int numContacts) { 
    ^
In file included from IOlist.c:4:0: 
functDefs.h:1:6: note: previous declaration of ‘writeToFile’ was here 
void writeToFile(struct contactId *contInfo, int numContacts); 
    ^
In file included from readFile.c:4:0, 
      from IOlist.c:6: 
contactStruct.h:1:8: error: redefinition of ‘struct contact’ 
struct contact { 
    ^
In file included from writeToFile.c:4:0, 
      from IOlist.c:5: 
contactStruct.h:1:8: note: originally defined here 
struct contact { 
     ^
+0

'這些錯誤以及'的東西部分來自於這樣一個事實,即在聲明writeToFile()函數之前,你並沒有確保編譯器知道'struct contactId'存在。原型中的類型僅在原型中已知。只需在函數頭的頂部添加'struct contactId;'行,這些問題就可能消失(或者會有一些不同的問題需要處理)。 –

回答

1

你的函數inputContactInfo()返回一個指向struct的指針。但是它試圖返回指針的地方是一個結構。您需要聲明struct contactId ** contactInfo,爲每個元素分配內存,然後您可以將指針正確地分配給contactInfo [i]。