简体   繁体   English

C 结构体中的未声明函数

[英]Undeclared Function within struct in C

I have the following code :我有以下code

#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);
}

I want to print the array that the *DomainName is pointing to or even just the pointer.我想打印*DomainName指向的数组,甚至只是指针。 However, I am getting this error message但是,我收到此错误消息

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

Do I need to declare the struct within the array or what?我需要在数组中声明结构还是什么?

You need to declare DomainData (which is an array of struct TopDomain structures) in a place that's visible at the point of the printf call.您需要在printf调用点可见的位置声明DomainData (它是struct TopDomain结构的数组)。

You've declared it inside a set of curly braces.您已经在一组花括号中声明了它。 The scope of the name extends from the declaration to the nearest enclosing } , which is just before the printf calls.名称的范围从声明扩展到最近的封闭} ,就在printf调用之前。 (Since it's static , its lifetime is the entire execution of the program, so the object still exists at that point. The problem is that its name is not visible.) (因为它是static ,它的生命周期是程序的整个执行过程,所以那个时候对象仍然存在。问题是它的名字不可见。)

Since DomainData depends on the declarations of struct TopDomain and enum flags , you'll need to move those as well.由于DomainData依赖于struct TopDomainenum flags的声明,因此您还需要移动它们。

(It rarely makes much sense to declare a type inside a compound statement.) (在复合语句中声明类型很少有意义。)

Incidentally, your format strings are incorrect.顺便说一句,您的格式字符串不正确。 In your first printf , you use %i for an argument of type char* ;在您的第一个printf ,您使用%i作为char*类型的参数; you want %s (assuming the pointer isn't NULL ).你想要%s (假设指针不是NULL )。 In your second you use %d for an argument of type unsigned int ;在您的第二个中,您将%d用于unsigned int类型的参数; you want %u (or 0x%x might be clearer in this case).你想要%u (或者0x%x在这种情况下可能更清楚)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM