这是我的程序的简化版本。
#include <stdio.h>
int main(void) {
char **words, **nwords;
int x;
words = malloc(sizeof *words * 1000);
if (words) {
for (x = 0; x < 20; x++) {
words[x] = malloc(sizeof *words[x] * 1);
}
}
nwords = malloc(sizeof *nwords * 1000);
if (nwords) {
for (x = 0; x < 20; x++) {
nwords[x] = malloc(sizeof(char) * 200);
//nwords[x] = "123456789012345"; // works correctly
nwords[x] = "1234567890123456"; // garbage
}
}
int i;
for (i=0; i<10;i++) {
sprintf(words[i],"%s",nwords[i]);
}
for (i=0; i<10;i++) {
printf("\n words[%d] = %s",i,words[i]);
}
return 0;
}
如果 nwords[x] 中的字符数增加超过 15,则最终 printf
开始打印奇怪的串联输出。 (参见 nwords[x] = "1234567890123456";//garbage
行)为什么会这样?我使用 malloc 给了它 200 个值得内存的字符。
最佳答案
有了这个声明
words[x] = malloc(sizeof *words[x] * 1);
您将单个字符分配给 words[x]
。然后你做
sprintf(words[i],"%s",nwords[i]);
将多个字符写入 words[i]
。
还有,用
nwords[x] = malloc(sizeof(char) * 200);
nwords[x] = "1234567890123456"; // garbage
你首先让 nwords[x]
指向你从堆中分配的一些内存,然后直接让它指向一个字符串文字。你可能想要任何一个
nwords[x] = malloc(sizeof(char) * 200);
strcpy(nwords[x], "1234567890123456");
或
nwords[x] = strdup("1234567890123456");
关于c - Malloc 二维数组可能大小溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20235412/