我正在用 C 编写一个名为 List Maker 的 Windows API 应用程序。
我有一个列表数据结构,如下所示:
typedef struct LMLIST
{
LPSTR filename;
char title[128];
char author[128];
BOOL openSuccess;
char *contents[];
int numLines;
}LMLIST;
但是,编译器会提示:
Error 1 error C2229: struct 'LMLIST' has an illegal zero-sized array c:\users\ian duncan\documents\github\listmakerforwindows\listmakerforwindows\listmakerlist.h 11 1 ListMakerForWindows
它指的是 char *contents[]
。
我的想法是有一个 char 数组,每个项目都是一个列表项,如下所示:
[0] List Item 1
[1] List Item 2
[2] List Item 3
...
很像 char *argv[]
这是否可能,如果不可能,还有其他方法吗?
最佳答案
使用char **contents
并动态分配字符指针数组:
LMLIST x;
...
x.contents = malloc(numstrings * sizeof (char *));
如果您不在其他地方存储字符串数,则需要将字符串数加一以为终止 NULL 指针腾出空间:
x.contents = malloc((numstrings + 1) * sizeof (char *));
x.contents[numstrings] = NULL;
本质上这就是 argv
的分配方式。
关于c - 如何在 C 中拥有像 'char *name[]' 这样的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21943206/