如何使用char-like';字符*名称[]和#x27;在C中?
我正在用C编写一个名为List Maker的Windows API应用程序 我有一个列表数据结构,如下所示:如何使用char-like';字符*名称[]和#x27;在C中?,c,char,C,Char,我正在用C编写一个名为List Maker的Windows API应用程序 我有一个列表数据结构,如下所示: typedef struct LMLIST { LPSTR filename; char title[128]; char author[128]; BOOL openSuccess; char *contents[]; int numLines; }LMLIST; [0] List Item 1 [1] List Item 2 [2
typedef struct LMLIST
{
LPSTR filename;
char title[128];
char author[128];
BOOL openSuccess;
char *contents[];
int numLines;
}LMLIST;
[0] List Item 1
[1] List Item 2
[2] List Item 3
...
但是,编译器抱怨:
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数组,每个项都是一个列表项,如下所示:
typedef struct LMLIST
{
LPSTR filename;
char title[128];
char author[128];
BOOL openSuccess;
char *contents[];
int numLines;
}LMLIST;
[0] List Item 1
[1] List Item 2
[2] List Item 3
...
很像char*argv[]
这可能吗?如果不可能,还有其他方法吗?使用
char**contents
并动态分配字符指针数组:
LMLIST x;
...
x.contents = malloc(numstrings * sizeof (char *));
如果未将字符串数存储在其他位置,则需要在字符串数中添加一个,以便为终止的空指针腾出空间:
x.contents = malloc((numstrings + 1) * sizeof (char *));
x.contents[numstrings] = NULL;
这就是
argv
分配的本质。使用char**contents
并动态分配字符指针数组:
LMLIST x;
...
x.contents = malloc(numstrings * sizeof (char *));
如果未将字符串数存储在其他位置,则需要在字符串数中添加一个,以便为终止的空指针腾出空间:
x.contents = malloc((numstrings + 1) * sizeof (char *));
x.contents[numstrings] = NULL;
这就是
argv
分配的本质。使用char**
和malloc
分配数组成员。使用char**
和malloc
分配数组成员