Search code examples
cpointerssubstrdel

Pointers On C exercises 6.18-2, my solution does not work


I'm a c beginer. learning C via the book ,below is my solution to 6.18-2 write a fucton to delete substr from source string.It does not work.

#include <stdio.h>

char *find_char(char const *source, char const *chars)
{
    int offset = 0;

    if (source == NULL || chars == NULL || *source == '\0' || *chars == '\0')
        return NULL;
    
    while (*chars != '\0')
    {
        while (*(source + offset) != '\0')
            if (*(source + offset++) == *chars)
                return source + --offset;

        chars++;
        offset = 0;
    }

    return NULL;
}

int del_substr(char *str, char const *substr)
{
    int offset = 0;
    int suboffset = 0;

    if (str == NULL || substr == NULL)
        return 0;
    while(*(str + offset) != '\0')
    {
        while( *(str + offset) != '\0' && *(str + offset++) == *(substr + suboffset++));
        if(*(substr + suboffset) == '\0')
        {
            while ((*(str + offset - suboffset) = *(str + offset++)) != '\0')
            ;
            return 1;
        }
        offset++;
        suboffset = 0;
    }

    return 0;
}


int main()
{
    char *source = "hello, people.";
    char *chars = "peo";

    del_substr(source, chars);
    printf("result:%s\n", source);

    return 0;
}

enter image description here


Solution

  • Both source and chars are pointers to string literals, you can't modify a string literal, as per the language rules, the behavior of a program where this is done is undefined. source must be declared as a char array:

    char source[] = "hello, people.";
    

    This way a copy of the string is stored in the array and, as such, it is modifiable.

    I'm going to guess that your book must talk about string literals and how you should handle them. If that is not the case, we can't really call it the book.