C Compare array elements using pointers
I'm trying to make a program to compare array elements using pointers and to give me some result; I make this simple program just to test if it works but I don't know why.. if i enter equals numbers nothing happes. So the first variable of the array is ptr so ptr + 1 means the next element, if i enter directly ch[0] == ch[1] it works. After that I want to make the program to compare characters if are the same.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int ch[2];
int *ptr = &ch;
scanf("%d%d", &ch[0], &ch[1]);
printf("Numbers to compare %d and %d", *ptr, *ptr + 1);
if (*ptr == *ptr + 1){
printf("Equals numbers\n");
}
return 0;
}
Solution 1:
Always remember a quick rule.
If the elements are i th
and i+1 th
index of some array, the the way to access them without using pointer is
a[i]
& a[i+1]
Now if you want to get the address of these values without using pointer, then you do &a[i]
and &a[i+1]
Now if you want to perform the above two tasks with pointer, then remember array name itself is a pointer to it. So if you want to get the address of i th
and i+1 th
element, the it will be simply
(a + i)
and (a + i + 1)
Now if you want to get the values at these locations, then simply de-reference it like
*(a + i)
and *(a + i + 1)
That's why in this case, it will be *ptr == *(ptr + 1)
Note: &a[i] is equivalent to (a+i)
and a[i] is equivalent to *(a+i)
Note 2: If you are not using Turbo C in windows system, then it is not recommended to use conio.h because it is not platform independent. I recommend you to move from Turbo C & conio.h