Ciprian Ambrus
Ciprian Ambrus

Reputation: 19

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;    
}

Upvotes: 1

Views: 6852

Answers (3)

Mayukh Sarkar
Mayukh Sarkar

Reputation: 2625

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

Upvotes: 3

CY5
CY5

Reputation: 1580

you are making mistake

  1. int *ptr=&ch;

  2. *ptr == *ptr + 1

  3. printf("Numbers to compare %d and %d",*ptr,*ptr+1);

  1. replace it with *ptr=ch becoz ch is an integer array so if you assign it directly to *ptr it will return the first address of ch i.e ch[0] address will be return

  2. difference between using *ptr+1 and *(ptr+1)

    *ptr+1 is similar to ch[0]+1
    and *(ptr+1) is similar to ch[1]

Explained

  1. you are doing *ptr+1 this will increment your first position of array ch so your output will Number to compare 1 and 2 even if your input is 1 and 5 replace it with *(ptr+1)

Upvotes: 0

TheQAGuy
TheQAGuy

Reputation: 494

To explain @kaylum comment which is correct: You had if (*ptr == *ptr + 1) now the *ptr part is correct but the right hand side of the == is incorrect because the way you have it your dereferencing ptr and then adding one to that value. However you want to increment ptr and then dereference hence why you need the ()

Upvotes: 0

Related Questions