-4

i'm reading the C programming language, question 2-4 asks to write a function called squeeze to delete all char in s1 which is in s2, so i write the code, but it can't run at all.

here is my code

#include <stdio.h>

void squeeze(char s1[], char s2[]);

int main()
{
    squeeze("tabcdge", "abc");
}

void squeeze(char s1[], char s2[])
{
    int i, j, k;

    for (i = k = 0; s1[i] != '\0'; i++) {
        for (j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++)
            ;
        if (s2[j] == '\0')
            s1[k++] = s1[i];
    }
    s1[k] = '\0';
    for (i = 0; s1[i] != '\0'; i++)
        printf("%c", s1[i]);
}
Micheal
  • 61
  • 8

3 Answers3

1

In main, you pass string constants to squeeze. But then squeeze tries to modify them with code like s1[k++] = s1[i]. You can't modify a constant -- that's what makes it a constant.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

String literals (like "tabcdge") are read-only. Attempting to modify one leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The String constatns are stored in read-only memory. As @Joachim said, modifying them (deleting in your case) is Undefined behaviour.

I suspect your program is crashing. For more info where the variables and constants are stored https://stackoverflow.com/a/18479996/3747770

Community
  • 1
  • 1
NJMR
  • 1,886
  • 1
  • 27
  • 46