线程1 exc_bad_access(代码=1地址=0x0)



我正在处理一个项目,其中我必须替换字符串中的一些字符。我看不懂其中一个错误。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void replaceLetters(char *text, char original, char new_char);
{
for (int counter = 0; text[counter] != ''; counter++)
{
if (text[counter] == original)//Error occurs here
{
text[counter] = new_char;
}
printf("%c", chr[counter]);
}
return 0;
}
int main()
{
char *text = "HallO";
char original = 'O';
char new_char = 'N';
replaceLetters(text, original, new_char);
return 0;
}

if语句中,会出现以下错误:thread 1 exc_bad_access (code=1 address=0x0)。这意味着什么,我该如何解决?

在c中,字符串文字如"HallO";存储在全局只读存储器中。如果要修改字符串,则需要将其保存在堆栈上的缓冲区中。

char text[6] = "HallO";

"这意味着什么,我该如何解决">

这是一种访问违规。您定义的字符串

char *text = "HallO";  

在C中被称为字符串文字,并在只读内存的区域中创建,导致访问冲突。

通过创建可编辑的原始变量,可以很容易地解决这一问题。例如:

char text[6] = "HallO"; //okay
char text[] = "HallO"; //better, let the compiler do the computation
char text[100] = "HallO"; //useful if you know changes to string will require more room

最新更新