我的编译器出现了标题中提到的错误。我不明白我做错了什么。有人可以向我解释一下吗?我已经有一段时间没有和 C 一起工作了。
char** answer(char c)
{
// Initial scanf and check
printf("Please input the character which you want to build your diamond with");
if (check(c) == true) {
printf("\n");
} else {
printf("Not a valid character");
return NULL;
}
//--------------------------------------------------------------------------------------------------------
//Preprocessing
//--------------------------------------------------------------------------------------------------------
//processing declarations
//Number of Rows
int pre_r = (int)c - 65;
int r = ( pre_r * 2 ) + 1;
//Declare the column of pointers
char *diamond[r];
//Declare the rwo of characters
// 2D array declared here to save on computation in situations where characters are not valid
for (int i=0; i<r; i++)
diamond[i] = (char*)malloc(c * sizeof(char));
//--------------------------------------------------------------------------------------------------------
//Postprocessing
//--------------------------------------------------------------------------------------------------------
return diamond;
free(diamond);
}
最佳答案
您有两个问题:
您无法返回函数本地变量的地址,因为它是在函数的堆栈帧中分配的,因此当函数返回时,它会与函数本身一起释放。
你使用
free()
是错误的,只有当你使用过malloc()
时才应该使用free()
,甚至不能使用已进行算术运算的指针,而只能使用由malloc()
/calloc()
/realloc() 之一返回的指针
。并且仅当您不再需要使用数据时,或者当您不再取消引用指针时更好。
试试这个,希望上面的解释+这段代码能帮助你理解
char **
answer(char columns)
{
int rows;
char **diamond;
printf("Please input the character which you want to build your diamond with");
if (check(columns) == true) {
printf("\n");
} else {
printf("Not a valid character");
return NULL;
}
rows = 2 * (columns - 'A') + 1;
diamond = malloc(rows * sizeof(*diamond));
if (diamond == NULL)
return NULL;
/* You must check for `NULL' for every `malloc()' */
for (int i = 0 ; i < rows ; i++)
diamond[i] = malloc(columns + 1); /* <- check for `NULL' */
/* ^
* if this is for a string you need space for the `nul' terminator
*/
return diamond;
}
此外,请使用有意义的变量名称,并且不要忘记为该代码中的每个 malloc()
调用 free()
,这由您决定。我相信你能弄清楚如何。
关于c - 我的 C 程序中函数返回局部变量错误的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899796/