Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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.

like image 934
user8426795 Avatar asked Jan 27 '23 06:01

user8426795


1 Answers

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
like image 192
ChilliDoughnuts Avatar answered Feb 07 '23 19:02

ChilliDoughnuts