我正在为一门基础类(class)编写一个非常简单的 C 程序,并且我一直在获得 EXC_BAD_ACCESS
在第 14 行。我看不出问题是什么。
该程序要求用户输入一个数字,然后显示与其关联的 ASCII 字符。
据我所知,只有在使用 lldb
调试我的程序时才会发生这种情况.从命令行或在 onlinegdb.com 上运行时,它工作得很好.
另外,如果我注释掉第 13 行,并分配 true
或 false
至 loop_ctrl
, 而不是 UserWantsToExit
的返回值,一切都按预期工作。
#include <stdio.h>
#include <stdbool.h>
void GetAndDisplayInput(void);
bool UserWantsToExit(void);
int main()
{
bool loop_ctrl = true;
while (loop_ctrl)
{
GetAndDisplayInput();
loop_ctrl = !UserWantsToExit(); /* EXC_BAD_ACCESS */
}
return 0;
}
void GetAndDisplayInput()
{
char input_char = '0';
printf("\nInput a number: ");
scanf("%i", &input_char);
getc(stdin); /* Gets rid of '\n' */
printf("\n\nIt's character '%c'!\n\n", input_char);
}
bool UserWantsToExit()
{
char choice = '0';
bool value = false;
printf("\nDo you want to exit? (Y/N): ");
scanf("%c", &choice);
getc(stdin); /* Gets rid of '\n' */
value = (choice == 'y' || choice == 'Y');
return value;
}
最佳答案
在函数 GetAdnDisplayInput()
中调用 scanf()
时使用的格式描述符 %i
需要一个相应的指针类型参数整数
。您正在传递指向 char
的指针。未定义的行为是未定义的。
请注意,您的 C 编译器应该警告您有关格式描述符和相应参数之间的不匹配;您应该养成在打开所有可能警告的情况下进行编译的习惯。
关于c - EXC_BAD_ACCESS 在函数调用后立即分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54131114/