c - 数组元素的类型不完整

标签 c arrays

所以基本上我应该制作一个程序来充当 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/

相关文章:

c++ - 在没有 super 用户的情况下在 linux 中打开 RAW 套接字

c - c中正则表达式在strcmp函数中的使用

objective-c - 填充 Objective C 中的第二个表

c - 如何只从字符串中提取数字?

c - 如何查找C代码中的段错误?

c - 如何允许 C 库使用调用者的日志记录?

我可以像访问数组一样访问指针吗?

arrays - 如何更新swift字典值

mysql - 使用 SQL 将 json 数据列表字段转换为列

java - 2d 整数数组无法正常运行 java android