c - C 结构中未声明的函数

标签 c arrays struct declaration

我有以下代码:

#include <stdio.h>
#include <string.h>

void getData() {

    static int HasDataBeenWritten;

    if (HasDataBeenWritten == 0) {

        enum flags
        {
            Country_NA = 1, 
            CountryUS = 2,
            CountryCN = 4, 
            CountryCA = 8, 
            Business_NA = 16,
            BusinessYes = 32,
            BusinessNo = 64,
            TypeOfEntityNonCommericial = 128,
            EntityPersonal = 256,
            EntityAll = 512,
        };

        struct TopDomain
        { 
            char *DomainName;
            unsigned int DataFlags:9;
        };          

        static struct TopDomain DomainData[8];

        static char DomainNameArray1[3] = {"EDU"};
        DomainData[0].DomainName = DomainNameArray1;    
        DomainData[0].DataFlags = 145;
        HasDataBeenWritten = 1;
    }

    printf("DomainData[0] : %i", (DomainData[0].DomainName));
    printf("DomainData[0] : %d", DomainData[0].DataFlags);
}

我想打印 *DomainName 指向的数组,甚至只是指针。但是,我收到此错误消息

getData.c:48:32 error: 'DomainData' undeclared (first use in this function) (printf("DomainData[0] : %i", (DomainData[0].DomainName));

我需要在数组中声明结构还是什么?

最佳答案

您需要在 printf 处可见的位置声明 DomainData(它是 struct TopDomain 结构的数组)打电话。

您已在一组大括号内声明了它。名称的范围从声明延伸到最近的封闭 },即在 printf 调用之前。 (由于它是静态,它的生命周期是程序的整个执行过程,因此该对象在此时仍然存在。问题是它的名称不可见。)

由于 DomainData 取决于 struct TopDomainenum flags 的声明,因此您还需要移动它们。

(在复合语句中声明类型几乎没有多大意义。)

顺便说一句,您的格式字符串不正确。在第一个 printf 中,您使用 %i 作为 char* 类型的参数;您需要 %s (假设指针不是 NULL)。在第二个中,您使用 %d 作为 unsigned int 类型的参数;你想要 %u (或者在这种情况下 0x%x 可能更清楚)。

关于c - C 结构中未声明的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034447/

相关文章:

c - (ORIG_EAX*4) 在 ptrace 调用中

c - Spin Loop 在缓存一致性方面的开销

python - 使用嵌套的 defaultdict 重建数组

c - 如何在C中合并结构体字段

C - 重新分配指针,它是结构 : dereferencing pointer to incomplete type 的属性

c - select() 和 read() 在串行端口读取时超时,但之前的 write() 成功?

c - OpenMP:并行内部同步

Java - 如何从数组中获取项目索引及其值?

javascript - 在具有相同 ID 的数组中添加/求和多个值

c - 指向结构行为的意外指针