传递和返回结构C

时间:2017-03-31 16:05:48

标签: c function struct

所以我遇到了这个问题,我只在我的main中得到错误代码(1)当我将结构保存在头文件中时结构已经被定义了(2)我使用了不兼容的指针类型。< / p>

#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 {
        ^

1 个答案:

答案 0 :(得分:1)

你的函数inputContactInfo()返回一个指向struct的指针。但它试图返回指针的地方是一个结构。你需要声明struct contactId ** contactInfo,为每个元素分配内存,然后你可以正确地将你的指针指向contactInfo [i]。