我想保留一个动态分配的字符串数组,使用c中的读系统调用读入。这里是什么,我试图做一个小样本:calloc/malloc并读取奇怪的行为?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void processInput() {
char ** array = (char **) calloc(20, sizeof(char*));
int arrayIndex = 0;
while(1) {
printf("Type something: ");
fflush(stdout);
char* buffer;
int readResult = read(0, buffer, 100);
array[arrayIndex] = (char*)calloc(readResult, sizeof(char));
}
}
然而,这会导致一些奇怪的问题:
Type something: a Type something: Type something: a Type something: Type something: abcdefg Type something: Type something: Type something: Type something: Type something: Type something: Type something: Type something:
有没有做任何解释?我似乎无法弄清楚为什么会发生这种情况。
'char * buffer; readResult = read(0,buffer,100);'使用未初始化的变量 - 特别是未初始化的指针 - 只能以泪结束。 – 2012-01-09 04:08:55
你并没有递增'arrayIndex' – Kevin 2012-01-09 04:13:41
不好意思,这个例子有点草率。你是正确的,我没有增加arrayIndex,但它不是重要的例子。但是,在实践中,你需要增加arrayIndex是100%正确的。否则,它不会存储索引0中最后添加的项目:P。 – Ryan 2012-01-09 04:17:09