【问题标题】:exception in for loop? [duplicate]for循环中的异常? [复制]
【发布时间】:2020-07-26 16:57:51
【问题描述】:

为什么我的代码返回:

例外:EXC_BAD_ACCESS(代码=2,地址=0x10d637fa2)

第一次进入for循环?

void unAnnoyWord(char *str) {
    char *out = str, mostAnnoying = 'a';
    do
    {
        if (*str != mostAnnoying)
        {
            *out = *str;
        }
    } while (*str++);
}

char *str = "hakuna matata";
unAnnoyWord(str);

【问题讨论】:

  • C 可能允许char *str = "hakuna matata",但这可以被视为语言缺陷。指向字符串文字的指针应始终声明为 const 限定。打开编译器警告。大多数人会告诉你这样做很危险。

标签: c exception


【解决方案1】:

也许这就是你想要的:

#include <stdio.h>

void unAnnoyWord(char *str) {
    char *out = str, mostAnnoying = 'a';
    do {
        if (*str != mostAnnoying) {
            *out++ = *str;
        }
    } while (*str++);
}

void main() {
  char str[] = "hakuna matata";
  char *sstr = str;
  printf("%s\n",sstr);
  unAnnoyWord(str);
  printf("%s\n",sstr);
}

导致:

hakuna matata
hkun mtt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多