简体   繁体   中英

C pointer arithmetic palindrome

I'm a java student who's currently learning about pointers and C. I tried to make a simple palindrome tester in C using a single array and pointer arithmetic. I got it to work without a loop (example for an array of size 10 :*(test) == *(test+9) was true. Having trouble with my loop. School me!

  #include<stdio.h>    

//function declaration
//int palindrome(int *test);

int main() 
{
    int output;
    int numArray[10] = {0,2,3,4,1,1,4,3,2,0};
    int *ptr;
    ptr = &numArray[0];
    output = palindrome(ptr);
    printf("%d", output);
}


//function determine if string is a palindrome
int palindrome(int *test) {    
    int i;
    for (i = 0; i <= (sizeof(test) / 2); i++) {    
        if (*(test + i) == *(test + (sizeof(test) - i)))    
            return 1;
        else 
            return 0;
    }
}

Why do you copy your pointer in another variable?

int *ptr;
ptr = &numArray[0];

Just send it to you function:

palindrome(numArray);

And sizeof(test) give you the memory size of a pointer, it's not what you want. You have to give the size in parameter of your function.

int palindrome(int *test, int size){
...
}

Finally your code must look like this:

#include<stdio.h>

int palindrome(int *test, int size);

int main() 
{
    int output;
    int numArray[10] = {0,2,3,4,1,1,4,3,2,0};
    output = palindrome(numArray, 10);
    printf("%d", output);
}


//function determine if string is a palindrome
int palindrome(int *test, int size) {    
    int i;
    for (i = 0; i < size / 2; i++) {    
        if (*(test + i) != *(test + (size - 1) - i))
            return 0;
    }
    return 1;
}

The Name of the array will itself acts as a pointer to an first element of the array, if you loose the pointer then there is no means for you to access the element of the array and hence you can send just the name of the array as a parameter to the function.

In the palindrome function:

you have used sizeof(test)/2. what happens is the address gets divided which is meaningless and hence you should not use that to calculate the mid element.

sizeof the pointer will be the same irrespective of the type of address that gets stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM