C Interview Questions on Pointers

We discuss various C Language interview questions on Pointers.

Interview Questions

  1. Why is a & operator used in relation to a Pointer?
  2. Why is a * operator used in relation to a Pointer?
  3. How are arrays and pointers related?
  4. Can you change the address pointed to by an array variable?
  5. What are Character Pointers?
  6. What is the result of this program?

Why is a & operator used in relation to a Pointer?

The unary operator & gives the address of an object. In the below example, pi = &i is read as pi is the address of i.

#include <stdio.h>

int main()
{
	int i;
	int *pi;
	
	pi = &i; //Read as "address of" i.
}

Why is a * operator used in relation to a Pointer?

The unary operator * is the indirection or dereferencing operator; In the below example, j = *pi. This is read as (j is the “value at” pi).

#include <stdio.h>

int main()
{
	int i = 10;
	int *pi;
	int j;
	
	pi = &i; //Read as "address of" i.
	
	j = *pi; // Read as "value at" pi.
}

How are arrays and pointers related?

An array variable stores the address of where the first element(index 0) of the array is stored. Hence an array variable is actually a pointer. In the above example marks is similar to a pointer.

Program below shows the different pointer operations that can be done on an array.

#include <stdio.h>

int main()
{
	int marks[] = {35,45,67};
	printf("%d\n",*marks);//35
	printf("%d\n",*(marks+1));//45
	printf("%d\n",*(marks+2));//67
	printf("%p\n",marks);//0x7fff57a3baac
}

Can you change the address pointed to by an array variable?

No. That’s actually one of the few differences between a normal pointer and an array. The value of a variable or expression of type array is the address of element zero of the array. An array name is not a variable; constructions like marks=pmarks and marks++ are illegal.

#include <stdio.h>

int main()
{

	int marks2 = {96,97,98};
	int marks[] = {35,45,67};
	int *pmarks;
	pmarks = marks2;
	
	marks = pmarks; //Not Allowed : Compilation Error

}

What are Character Pointers?

Below program shows an example of character pointer.

#include <stdio.h>

int main()
{
	char* text = "Something";
}

What is the result of this program?

#include <stdio.h>

void swap(int *pi, int *pj) //Definition of Function
{
	int temp = *pi;
	*pi = *pj;
	*pj = temp;
}


int main()
{
	int a=5, b=6;
	swap(&a,&b);
	printf("a:%d,b:%d",a,b);//a:6,b:5a
}

In the program above, the values a and b are swapped. The address of the variables a and b are passed to the function. So, the function modifies the original values.

FREE JAVA INTERVIEW GUIDE

ONE SUBSCRIBER EVERY MONTH WINS 100% DISCOUNT CODE FOR INTERVIEW GUIDE WITH 23 VIDEOS

We Respect Your Privacy