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
.