【发布时间】:2017-05-09 16:18:19
【问题描述】:
我的二维数组 char **buffer 正在创建中。 malloc 部分有效。 realloc 部分正在生成分段错误。
这些是执行以下操作的 2 个函数;
//sets up the array initially
void setBuffer(){
buffer = (char**)malloc(sizeof(char*)*buf_x);
for(int x=0;x<buf_x;x++){
buffer[x] = (char *)malloc(sizeof(char)*buf_y);
}
if(buffer==NULL){
perror("\nError: Failed to allocate memory");
}
}
//changes size
//variable buf_x has been modified
void adjustBuffer(){
for(int x=prev_x; x<buf_x;x++) {
buffer[x] = NULL;
}
buffer=(char**)realloc(buffer,sizeof(char*)*buf_x);
for(int x=0; x<buf_x;x++){
buffer[x] = (char*)realloc(buffer[x],sizeof(char)*buf_y);
strcpy(buffer[x],output_buffer[x]);
}
if(buffer == NULL){
perror("\nError: Failed to adjust memory");
}
}
【问题讨论】:
-
但是我怎样才能改变缓冲区的大小,同时不删除其中的元素呢?还是应该将元素保存在数组中,然后将它们放回重新分配的元素中?谢谢
-
@xing 我已经修改了代码。你能检查一下我是否听从了你的建议。谢谢
-
这是一个锯齿状数组,而不是二维数组!完全不同的数据类型!
-
@xing 所以我应该在函数adjustBuffer的开头设置buffer[0] = NULL吗?谢谢