user8426795
user8426795

Reputation: 79

Pointers and Arrays in C. The Concept Not Quite Clicking.

I am doing practice in C by making a program that checks whether an array of chars is a palindrome or not by using pointers. I am still a little iffy on pointers in general, but I have no clue why this program is not working. It gives the correct output for single letter checks but for more than one character it always returns "is not a palindrome". I am really sorry if this is not a good question, but I would really like to learn what I am doing wrong so that I can grasp the concept of pointers better.

This is the program:

int is_palindrome2(const char *phrase, int length)
{
  char i = 0;
  const char *end;

  phrase = &i;
  end = phrase + length - 1;

  while(phrase < end)
  {
    if((*phrase) != (*end))
    {
      return 0;
    }
    phrase++;
    end--;
  }

  return 1;

}

And this is what output I get from the command prompt(The first test was by subscription and the second test is this function)

Testing #1: a is a palindrome
Testing #2: a is a palindrome

Testing #1: ab is not a palindrome
Testing #2: ab is not a palindrome

Testing #1: aa is a palindrome
Testing #2: aa is not a palindrome

Testing #1: abcdcba is a palindrome
Testing #2: abcdcba is not a palindrome

Testing #1: madamImadam is a palindrome
Testing #2: madamImadam is not a palindrome

Thank you for your time.

Upvotes: 4

Views: 106

Answers (3)

ChilliDoughnuts
ChilliDoughnuts

Reputation: 377

Here's a more visual explanation of what's happening, for those interested.

char array[] = "abba";
is_palindrome2(array,4);

array is convertible to a pointer that points like this

| 'a' | 'b' | 'b' | 'a' | NULL |
   ^
 array

So when you call the function, you can imagine the pointer pointing towards

| 'a' | 'b' | 'b' | 'a' | NULL |
   ^
 phrase

When you do

char i = 0;
phrase = &i;

You actually reassign the pointer to point towards somewhere else.

| 'a' | 'b' | 'b' | 'a' | NULL |       ...       | 0 |
                                                   ^
                                                phrase

Upvotes: 4

Kon
Kon

Reputation: 4099

You need to remove phrase = &i;, it overwrites the phrase pointer.

Also, keep in mind that when calling your function (as it's currently implemented), length should be exclusive of the null character.

Upvotes: 1

dbush
dbush

Reputation: 223937

Here's the problem:

phrase = &i;

You're overwriting the value of phrase, which points to your string, with the address of an unrelated local variable. Then any pointer arithmetic you perform on phrase works off of the address of i. This will invoke undefined behavior if length is greater than 1 because the pointer arithmetic will take you past the bounds of i (or one address past i).

There's no need for that statement. Get rid of it, and phrase starts at the start of the string as it should.

Upvotes: 3

Related Questions