exception in for loop? [duplicate]

烂漫一生 提交于 2021-02-17 05:15:38

问题


Why my code returns:

Exception: EXC_BAD_ACCESS (code=2, address=0x10d637fa2)

in the first time it enters the for loops?

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

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

回答1:


Perhaps this is what you want:

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

Resulting in:

hakuna matata
hkun mtt


来源:https://stackoverflow.com/questions/63103133/exception-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!