[英]thread 1 exc_bad_access (code=1 address=0x0)
I'm working on a project where I have to replace some char in a string.我正在做一个项目,我必须替换字符串中的一些字符。 I do not understand one of the errors I see.我不明白我看到的错误之一。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void replaceLetters(char *text, char original, char new_char);
{
for (int counter = 0; text[counter] != '\0'; 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;
}
At the if
statement the following error occurs: thread 1 exc_bad_access (code=1 address=0x0)
.在if
语句中发生以下错误: thread 1 exc_bad_access (code=1 address=0x0)
。 What does this mean, and how can I address it?这是什么意思,我该如何解决?
In c, string literals like "HallO" are stored in global read-only memory.在 c 中,像“HallO”这样的字符串文字存储在全局只读内存中。 If you want to modify the string, you will need to keep it in a buffer on the stack.如果要修改字符串,则需要将其保存在堆栈的缓冲区中。
char text[6] = "HallO";
"What does this mean, and how can I address it?" “这是什么意思,我该如何解决?”
It is an access violation.这是访问冲突。 The string you have defined你定义的字符串
char *text = "HallO";
is referred to in C as a string literal , and is created in an area of read-only memory, resulting in an access violation.在 C 中被称为字符串文字,并在只读内存区域中创建,从而导致访问冲突。
This can be easily addressed by creating the original variable such that it is editable.这可以通过创建原始变量使其可编辑来轻松解决。 eg:例如:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.