c - 重新分配结构
问题描述
我有一个可以修改的 2d char 数组的结构,我应该能够增加 2d 数组中的行数,我设法做到了,但我遇到了一个问题,在第四行之后我无法分配更多空间,我尝试将数组的长度更改为更小,在这种情况下,同样的问题在四次后一致,并且 realloc() 的返回值不是 NULL,我无法退出程序。
这是结构:
struct Buffer{
/*--buffer--*/
/*2d array that store the whole text */
char **text;
/* number of rows */
int count;
};
程序读取文本并在 60 个字符后创建一个新行
/*initialize a buffer */
struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
buffer->text = (char**)malloc(sizeof(char*));
buffer->text[0] = (char*)malloc(sizeof(char)*61);
buffer->count = 1;
/*start reading the text*/
readText(1, buffer);
printf("\nFixed output: \n");
/*print the text*/
printText(1, buffer);
在 readText() 里面
/* try to add more memory for the ADT */
buffer->text[buffer->count-1][60] = '\0';
if(!expandADT(1, buffer)) exit_error(0);
buffer->text[buffer->count-1][0] = c;
int expandADT(int option, void *ptr)
/* cast the pointer */
struct Buffer* buffer = (struct Buffer*) ptr;
struct Buffer* temp;
/* increase the number of rows */
buffer->count++;
/* try to make space for another row */
temp = (struct Buffer*)realloc(buffer, sizeof(*buffer->text) * buffer->count);
/* if the buffer is NULL it means that we don't have enough space and we return an error*/
if(temp == NULL) return 0;
buffer = temp;
buffer->text[buffer->count-1] = (char*)malloc(sizeof(char)*61);
if(buffer->text[buffer->count-1] == 0) return 0;
如果数组空间不足,它应该打印一条消息并关闭程序,但是术语
if(temp == NULL) return 0;
在expandADT()中不正确,程序继续运行。然后它停在代码行 -
buffer->text[buffer->count-1][0] = c; /* c is an input character */
在程序尝试扩展数组之后的readText()处。
对于大于 60*4 的输入。该程序没有任何输出,它会关闭。
解决方案
推荐阅读
- python - ImportError 无法从“pptx.enum.shapes”导入名称“MSO_AUTO”
- haskell - 麻烦将矩阵加在一起
- foreach - Terraform,您可以使用 for_each 创建 X 数量的资源吗?
- ansible - 成功执行远程操作后连接错误
- dictionary - 如何用另一个地图替换地图的值?
- ruby-on-rails - RSpec 和 Capybara:如何让 have_css 带有文本:忽略文本中的换行符
- javascript - 如何在 Node.js 中正确设置猫鼬方法 createConnection
- cypress - 如何使用赛普拉斯将元素移动到块中?
- node.js - 在 Node.js 中如何注意到缺少的功能?
- list - 在 XML 文件中保存游戏对象的数据时出现问题