数组元素的类型不完整

时间:2015-01-23 03:38:06

标签: c arrays

所以基本上我应该制作一个程序,作为5个不同“网站”的密码管理器。当我在一个文件中声明函数和main方法时,它运行完美。但是,当我使用头文件时,我收到错误

functions.h

#ifndef FUNCTIONS_H_  
#define FUNCTIONS_H_

struct entry;

void requestEntry(struct entry *data);
void displaySummary(struct entry *data);
void displayEntry(struct entry *data);

#endif

functions.c

#include <stdio.h>
#include "functions.h"

struct entry{
    char webName[32];
    char userName[32];
    char password[32];
};

void requestEntry(struct entry *data){
    printf("Please enter the following items: \n");
    printf("Website name: ");
    scanf("%s", data->webName);
    printf("Username: ");
    scanf("%s", data->userName);
    printf("Password: ");
    scanf("%s", data->password);
}

void displaySummary(struct entry *data){
    printf(" - %s\n", data->webName);
}

void displayEntry(struct entry *data){
    printf("Website: %s\n", data->webName);
    printf("Username: %s\n", data->userName);
    printf("Password: %s\n", data->password);

}

的main.c

#include <stdio.h>
#include <stdbool.h>
#include "functions.h"

int main()
{
struct entry sites[5];

for (int i = 0; i < 5; i++){
    requestEntry(&sites[i]);
}

printf("\n");
printf("Summary: \n");

for (int i = 0; i < 5; i++){
    printf("%d", (i + 1));
    displaySummary(&sites[i]);
}

bool cont = true;
int i;

while (cont){
    printf("Type in a number from 1 to 5 to pull up the entry, or type 0 to exit: ");
    scanf("%d", &i);
    if (i == 0){
        cont = false;
        continue;
    }
    printf("\n");
    displayEntry(&sites[i - 1]);
}
}

错误:数组'入口网站[5]'的元素具有不完整的类型

我尝试在不同的IDE中构建程序,它说我的数组大小太大,显然只有5个结构。我知道我的代码确实有效,因为就像我说的那样,当一切都在一个文件中时,它运行得很好。

2 个答案:

答案 0 :(得分:1)

您无法在struct entry的定义不可见的地方声明struct entry数组;编译器不知道制作数组的每个元素有多大。

在您的情况下,直截了当的是将struct entry的定义从functions.c移到functions.h。

答案 1 :(得分:1)

这种分离的问题在于struct entry的内部结构变为私有functions.c翻译单元。这可能是也可能不是。

  • 如果您希望将struct设为私有,请切换到动态分配
  • 如果您不介意公开struct,请将其定义移至标题文件。

这是第一种方法:在标题中添加一个函数

struct entry *allocateEntries(size_t count);

通过调用functions.cmalloc(sizeof(struct entry)*count)文件中定义此功能。现在你可以替换

struct entry sites[5];

struct entry *sites = allocateEntries(5);

不要忘记将free(sites)添加到main()的末尾。

相关问题