c - 如何在 C 中拥有像 'char *name[]' 这样的字符?

标签 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;

但是,编译器会提示:

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/

相关文章:

c - 尝试在单个程序中打印字符、以空格结尾的字符串和以换行符结尾的字符串

Python:如何从字符数据流中生成整数?

java - 在 Java 中访问嵌套列表数组时遇到问题

c - GLSL 布局属性编号

c - 为什么使用 asprintf() 而不是 sprintf()?

c++ - 程序以信号 25 终止,超出文件大小限制;为什么?

c++ - 在指定位置插入字符

将十六进制字符串 (char []) 转换为 int?

c - C 语言老虎机 (gotoxy)

c - 使用 MPI(C 语言)代码的矩阵乘法无法在超过 6 个节点上运行