我在结构中有一个数组,如下所示:
typedef struct mystruct{
const char *myarr[30];
} mystruct;
稍后我需要在程序中通过创建新数组、复制内容然后更改 myarr 以指向新数组来将此数组增加到 60 个元素。
我尝试了以下方法:
const char newtable[n];
s->*myarr = newtable;
但是 gcc 提示:
error: incompatible types in assignment
关于实现此目标的正确方法有什么想法吗?
最佳答案
假设您确实希望您的数组包含 char *
,而不是 char
,您应该像这样定义您的结构:
typedef struct {
const char **myarr;
/* I assume you actually have more members here */
} mystruct;
然后像这样初始化它:
mystruct s;
s.myarr = (const char **) malloc(30 * sizeof(const char *));
if (!s.myarr) { /* handle out-of-memory condition somehow */ }
然后您可以稍后使用 realloc()
扩展它:
const char **tmp = (const char **) realloc(s.myarr, 60 * sizeof(const char *));
if (tmp) s.myarr = tmp;
else { /* handle out-of-memory condition somehow */ }
(请注意,如果 realloc()
返回 NULL
,s.myarr
的原始值仍然有效。)
关于C 将数组的指针更改为更大的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7708331/