Comparing, Printing, returning Pointer in C

Written by

Namrata Jangid

Comparing pointer in C:

All valid relational operators in C can be used for comparing pointers. However, pointers can be compared only if they point to the same array.
Consider the code snippet below, it shows comparison between the same type of pointers:

int main()
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = (int *)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from Ptr1");
printf("Ptr1 is far from Ptr2");

The above code gives the following output:

Ptr2 is far from Ptr1

Printing pointers in C:

We can use the %p format specifier in the printf to print the value of a pointer. However, for doing so, we need to convert the pointer to void * type.
The below code snippet explains this concept:

int main()
int num = 10;
int *ptr = #
printf("&ptr   = %p\n", (void *) &ptr);
printf("ptr    = %p\n", (void *) ptr);

The above code snippet gives the following output:

&ptr   = 0x7ffd28c0c010
ptr    = 0x7ffd28c0c01c

Returning pointers from functions in C:

A function can return a pointer in C. We need to specify in the function signature that the function will return a pointer.
The syntax for returning a pointer from a function is as follows:

returnType *functionName(param list);
  • returnTypeis the type of the pointer that will be returned by the function functionName.
  • param listis the list of parameters of the function.

For example:

  • int * add(int x, int y)
  • long * add(long a, long b)

Let us look at a code snippet where we return a pointer from a function:

#include <stdio.h>
int *getMax(int *m, int *n) {
* if the value pointed by pointer m is greater than n
* then, return the address stored in the pointer variable m else return the address stored in the pointer variable n
if (*m > *n) {
return m;
else {
return n;
int main(void) {
int x = 12;
int y = 15;
int *max = NULL;// pointer variable
max = getMax(&x, &y);//passing the address of x and y * to the function getMax()
printf("Maximum value: %d\n", *max);
return 0;

The output will be:

Maximum value: 15
Comparing, Printing, returning Pointer in C