-1

Ok, I have a function to check if a number is a palindrome (it is not completed yet) which calls a function called copystring().

If I have

putchar(*destination)

Within the copystring() function loop, it outputs the destination string as it should. However, the original string within the is_palindrome function is not being edited. It remains blank. Why is this happening and how can I fix it?

int is_palindrome(int num)
{
    char buffer[30];
    char reversebuffer[30];
    sprintf(buffer, "%d", num);

    copystring(reversebuffer, buffer);
    reversestring(reversebuffer, strlen(reversebuffer));
}

void copystring(char *destination, char *source)
{
    while (*source){
        *destination = *source;
        ++source;
        ++destination;

    }
    *destination = '\0';
}
SAT
  • 647
  • 1
  • 12
  • 23
Dylan
  • 159
  • 5
  • 1
    Why aren't you using the standard `strcpy()`? – Barmar Jan 09 '14 at 08:55
  • 7
    Post the source for `reversestring()` or make absolutely sure that the bug isn't in that function. `copystring()` works fine for me. – svk Jan 09 '14 at 08:55
  • 1
    Which _original string_ are you referring to? `buffer` or `reversebuffer`? What makes you think it's blank? Show your code that demonstrates this. – Barmar Jan 09 '14 at 08:59
  • buffer is the original, i am trying to copy its contents into reverse buffer. printf() on reversebuffer immediately after calling copystring() gives no output – Dylan Jan 09 '14 at 09:02
  • It is working for me http://codepad.org/wGYNSjVL –  Jan 09 '14 at 09:06
  • yes it was working for me at one point in another program but that was called directly from main. I tried using strcpy() instead, which works fine. However, as soon as I call copystring() instead it does not work – Dylan Jan 09 '14 at 09:09
  • Did you try to run your program with a debugger ? I don't see any problems in your copystring function. – Jabberwocky Jan 09 '14 at 09:22
  • @MichaelWalz No, I'm fairly new to programming. I have gdb installed on my system but don't know how to use it. – Dylan Jan 09 '14 at 09:30
  • Well, then it's about time to start learning how to use gdb. It's very powerful and it will help you greatly to understand what's happening in the software you write. – Jabberwocky Jan 09 '14 at 09:34

2 Answers2

1

I don't understand the issue, it works for me fine. Anyway, you are working too hard for it. It would be much more efficient to write something like:

bool is_palindrome2(int num)
{
    char buffer[30];
    sprintf_s(buffer, "%d", num);
    int length = strlen(buffer);

    for(int i=0; i < length/2 ; i++)
    {
        if(buffer[i] != buffer[length - i - 1])
            return false;
    }

    return true;
}
Uri Y
  • 840
  • 5
  • 13
-1

In the end of copy string() function both destination and source pointers are pointing to '\0' character, so if call putchar(*destination) or putchar(*source), they will print blank.