我试图在二维指针数组中存储一个句子列表。下面的代码在循环声明之后给出了一个分段错误(我用printf语句检查;循环中没有语句执行):
int main( int argc, char** argv){
char *inputarray[MAX_LINE];
int count = 0;
//char cpy[MAX_LENGTH] <---- This one doesn't work either
char *cpy = (char*) calloc (MAX_LENGTH, sizeof(char));
while ( count <= MAX_LINE && fgets(cpy, MAX_LENGTH, stdin)){
int str_len = strlen(cpy);
cpy[--str_len] = '\0';
inputarray[count++] = reverse(cpy, str_len);
}
printOutput(inputarray, count);
return 0;
}
现在已经尝试调试3个多小时但没有用。帮助任何人?
答案 0 :(得分:1)
您只将MAX_LINE
元素分配给指向char的指针数组。
0
开始。count < MAX_LINE
)而非(count <= MAX_LINE
)实施例:
假设您已分配*inputaray[5];
这就是发生的事情,
count=0; //1st sentence
count=1; //2nd sentence
count=2; //3rd sentence
count=3; //4th sentence
count=4; //5th sentence
在上面的代码中,
count=5; //which is <=5
因此尝试将输入字符串存储到无效的内存中。