【问题标题】:thread 1 exc_bad_access (code=1 address=0x0)线程 1 exc_bad_access(代码=1 地址=0x0)
【发布时间】:2020-11-18 20:06:19
【问题描述】:

我正在做一个项目,我必须替换字符串中的一些字符。 我不明白我看到的错误之一。

#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;
}

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

【问题讨论】:

标签: c


【解决方案1】:

在 c 中,像 "HallO" 这样的字符串字面量存储在全局只读内存中。如果要修改字符串,则需要将其保存在堆栈上的缓冲区中。

  char text[6] = "HallO";

【讨论】:

  • 顺便说一句,您通常最好使用char text[] = ...,这样您就不必计算大小。
【解决方案2】:

“这是什么意思,我该如何解决?”

这是访问冲突。你定义的字符串

char *text = "HallO";  

在 C 中称为string literal,并在只读内存区域中创建,从而导致访问冲突。

这可以通过创建可编辑的原始变量轻松解决。例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多