0

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
    C may allow `char *str = "hakuna matata"`, but that can be considered a language defect. Pointers to string literals should always be declared const qualified. Turn on your compiler warnings. Most will tell you it's dangerous to do what you did. – StoryTeller - Unslander Monica Jul 26 '20 at 17:06

1 Answers1

0

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
Gerard H. Pille
  • 2,528
  • 1
  • 13
  • 17