Search code examples
arrayscpass-by-referencec-stringspalindrome

my C function is modifying a char array it shouldn't because it's deliberately out of scope


I wrote a little program in C that checks if a word of phrase is a palindrome. One function does the checking after calling another function to remove the spaces in a phrase. The app first asks the user to enter a word or phrase. Then it strips out the spaces in a separate function then evaluates the function to see if its a palindrome and return a bool... The printf statements use the original string (or should) but the resulting printf uses the modified string instead. I don't see where is gets it. Here is the code:

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

bool isPalindrome(char string[]);
char* stripSpaces(char *noSpace);

int main(void)
{
    char usrStr[250];


    printf("Please enter a string and I will check if it is a palindrome...");
    scanf( "%250[^\n]", usrStr);
    
    printf("\n");
    isPalindrome(usrStr) ? printf("\"%s\" is a palindrome", usrStr) : printf("\"%s\" is not a palindrome", usrStr);

    printf("\n");

    return 0;
}

bool isPalindrome(char* string)
{
    char* newStr = stripSpaces(string);
    
    int middle = strlen(newStr) / 2;
    int len = strlen(newStr);

    for(int x = 0; x < middle; x++)
        if(newStr[x] != newStr[len - x - 1])
            return false;  
    // Check first char againse last char - then 2 char against 2nd last char and so on until mismatch found.
    // If no mismatch then the string is a palindrome
    
    return true;
}

char* stripSpaces(char *noSpace)
{
    int length = strlen(noSpace);
    int count = 0;
    for(int idx = 0; idx < length; idx++)
    {
        if(noSpace[idx] != ' ')
        {
            noSpace[count] = noSpace[idx];
            count++;
        }
    }
    noSpace[count] = '\0';

    return noSpace;

}

Any thoughts? Cheers Charles

I tried making usrStr a const to no avail. I expected usrStr to not get modified as it is out of scope in the stripSpaces function.


Solution

  • noSpace is a pointer. If you change a pointer it will change out of scope too.

    for a new string you can use malloc

    char* stripSpaces(char *noSpace)
    {
        int length = strlen(noSpace);
        char *ret = malloc( length );
        int count = 0;
        for(int idx = 0; idx < length; idx++)
        {
            if(noSpace[idx] != ' ')
            {
                ret[count++] = noSpace[idx];
            }
        }
        ret[count] = '\0';
    
        return ret;
    
    }