【发布时间】:2018-08-19 10:49:19
【问题描述】:
我正在尝试从用户那里获取字符串,然后如果他们输入一个长字符串,则扩展字符串的大小,如果他们输入的字符串比预期的多,我还会扩展保存字符串的数组的大小。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int main(int argc, char* argv[])
{
int number_of_strings = 5;
int string_size = 5;
int count = 0;
char **array = (char**)calloc(number_of_strings, sizeof(char*));
for (int i = 0; i < number_of_strings; i++)
{
array[i] = (char*)calloc(string_size + 1, sizeof(char));
}
////////////////////////////MAIN PART///////////////////////////////////////////////
int arr_size = number_of_strings;
int str_count = 0; //Total number of input strings counter
for (int j = 0; j < arr_size; j++)
{
if (arr_size >= str_count) //Check if the number of input strings is more than expected
{
array = (char**)realloc(array, (arr_size + 1) * sizeof(char*)); //allocate memory for 1 more string
arr_size++; //Increase the loop rounds
}
int str_size = string_size;
int char_count = 0; //Total number of input characters counter
for (int h = 0; h < str_size; h++)
{
if (str_size >= char_count) //Check if the input string size is more than expected
{
array[j] = (char*)realloc(array[j], (str_size + 1) * sizeof(char)); //allocate memory for 1 more char
str_size++; //Increase the loop rounds
}
scanf(" %c", &array[j][h]); //get a single char
char_count++; //Increment the total input character count
}
str_count++; //Increment the total input string count
}
////////////////////////////////////////////////////////////////////////////////////
for (int k = 0; k < number_of_strings; k++)
{
printf("%s", array[k]);
free(array[k]);
}
free(array);
return 0;
}
输入:这不是看起来的样子,但我不知道为什么会这样
输出:空标准输出。超过时间限制
预期输出:这不是它看起来的样子,但我不知道为什么会发生这种情况
程序等待用户输入很长时间,即使用户没有输入任何输入,它也不会停止扫描输入,因此最终程序崩溃。
我认为错误是由于数组重新分配不当引起的。非常感谢任何关于为什么会导致此错误以及如何修复它的想法。谢谢!
【问题讨论】:
-
将其减少到 只是有问题的部分的minimal reproducible example。我们不是来调试这样的完整程序的。并且不要从
malloc()转换返回值。
标签: c memory multidimensional-array memory-management