Failed to manipulate the string passed as pointer to pointer inside the function

56 Views Asked by At

I am creating a removeNonAlphaCharacters function trying to remove all non alphabetic characters using C.

I could remove all non-alphabetic characters inside the function, but I can not pass the modified string back the original string, which means I can't override the original string directly inside the function even using double pointer. Does anyone have an idea what's going wrong in my code?

The final printf inside the main function won't print me the HelloData for me, however the one inside the removeNonAlphaCharacters function could give me the correct output.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int removeNonAlphaCharacters(char ** source);

int main() {
    char * source = "Hello 2 Data!";
    char **sourcePointer = &source;
    int result = 0;
    result = removeNonAlphaCharacters(sourcePointer);
    printf("we have successfully removed %i characters from the string.\n", result);
    printf("The modified result is: %s", source);
    return 0;
}

int removeNonAlphaCharacters(char ** source) {
    char *dest = *source;
    size_t sourceLength = strnlen(*source, 100);
    char *str = malloc(sourceLength*sizeof(char));
    int removeNum = 0;
    for (; *dest != '\0'; dest++) {
        if (*dest >= 'A' && *dest <= 'Z' || *dest >= 'a' && *dest <= 'z') {
            *str = *dest;
            str++;
        }
        else {
            removeNum++;
            continue;
        }
    }
    printf("The modified result is: %s\n", str-(sourceLength-removeNum));
    *source = malloc((sourceLength-removeNum) * sizeof(char));
    strncpy(*source, str, 100);
    return removeNum;

I tried to use malloc to allocate memory inside the function, and it didn't work for me. And I also tried directly override the original string inside the removeNonAlphaCharacters function without allocating memory, which will end up into the Memory Error SIGBUS.

1

There are 1 best solutions below

1
xulo On

The issue you have is within your function, removeNonAlphaCharacters.

You create a new string str (i.e. a pointer to a char) and as you manipulate this string, your pointer is incrementing (in the line str++) hence when you call the function strncpy, the string you are copying is a pointer to the end of the string you want (not a pointer to the start).

To fix, modify the line containing strncpy to be

strncpy(*source, str-(sourceLength-removeNum), 100);

Don't forget as well to consider adding the null termination '\0' to your new string.