所以基本上我应该制作一个程序来充当 5 个不同“网站”的密码管理器。当我在一个文件中声明所有函数和主要方法时,它运行得很好。但是,当我使用头文件时,我收到显示的错误
函数.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
函数.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 个结构。我知道我的代码确实有效,因为就像我说的,当所有内容都在一个文件中时,它可以完美运行。
最佳答案
这种分离的问题是,结构条目
的内部结构对于functions.c
翻译单元来说是私有(private)的。这可能是可取的,也可能不是可取的。
- 如果您希望将
struct
保持私有(private),请切换到动态分配 - 如果您不介意公开您的
结构
,请将其定义移至头文件中。
这是第一种方法:向 header 添加函数
struct entry *allocateEntries(size_t count);
通过调用 malloc(sizeof(struct entry)*count)
在 functions.c
文件中定义此函数。现在您可以替换
struct entry sites[5];
与
struct entry *sites = allocateEntries(5);
不要忘记将 free(sites)
添加到 main()
的末尾。
关于c - 数组元素的类型不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102625/