如何在其中定义多个字符串的结构?

时间:2018-12-11 16:18:01

标签: c

我想在C头文件中定义一个结构,该头文件包含多个字符串。 例如,下面列出了3个文件,并定义了struct fileList。

#include <stdio.h>

#define FILE1 "/data/file1"
#define FILE2 "/data/file2"
#define FILE3 "/data/file3"

typedef struct fileList{
    FILE1;
    FILE2;
    FILE3;
}fileList;

int main()
{
    fileList fl;
    printf("Hello world! %s\n", fl.FILE1);

}

但是当我运行它时,出现了以下错误。 为什么?您有更好的解决方案吗? 谢谢!

gcc test.c 
test.c:3:15: error: expected specifier-qualifier-list before string constant
 #define FILE1 "/data/file1"
               ^
test.c:8:5: note: in expansion of macro ‘FILE1’
     FILE1;
     ^
test.c: In function ‘main’:
test.c:3:15: error: expected identifier before string constant
 #define FILE1 "/data/file1"
               ^
test.c:16:36: note: in expansion of macro ‘FILE1’
     printf("Hello world! %s\n", fl.FILE1);

2 个答案:

答案 0 :(得分:1)

#define宏视为被搜索和替换的宏。如果将宏替换为其定义,则会得到:

typedef struct fileList{
    "/data/file1";
    "/data/file2";
    "/data/file3";
}fileList;

printf("Hello world! %s\n", fl."/data/file1");

这些代码段在语法上显然无效。


您似乎正在尝试创建具有三个字符串字段的结构。一种方法是:

typedef struct fileList {
    const char *file1;
    const char *file2;
    const char *file3;
} fileList;

然后,如果要创建该结构的实例并将这些字符串字段的 values 设置为列出的字符串文字,则可以编写:

int main() {
    fileList fl;
    fl.file1 = "/data/file1";
    fl.file2 = "/data/file2";
    fl.file3 = "/data/file3";
    printf("Hello world! %s\n", fl.file1);
}

根本不需要预处理器宏。

答案 1 :(得分:0)

关于:

typedef struct fileList{
    FILE1;
    FILE2;
    FILE3;
}fileList;

这不会产生有效的数据项。建议:

struct fileList{
    char *FILE1;
    char *FILE2;
    char *FILE3;
};
typedef struct fileList  fileList;