1) Which operator is used to get the "content of a variable pointed to by a pointer"?
- Dot Operator (.)
- Address of Operator (&)
- Indirection or De-reference Operator (*)
- Arrow Operator (→)
Correct answer: 3
Indirection or De-reference Operator (*)
2) What will be the type of a pointer, which is pointing to an integer variable?
- int *
- long int *
- char *
- unsigned *
Correct answer: 1
int *
To store the address of an integer variable, we need to declare an integer pointer (int *).
3) If ptr is a pointer to one dimensional array, which statement will return the value of 3rd element?
- (ptr+3)
- *(ptr+3)
- (&ptr+3)
- *ptr+3
Correct answer: 2
*(ptr+3)
ptr will point to the address of one-dimensional array and * (indirection or de-reference operator) returns the value of variable pointed by a pointer, thus *(ptr+3) will return the value of 3rd element of array.
4) Consider the given declaration:
int* ptr1,ptr2;
What is the type of ptr2 here?
- int * (Integer pointer)
- void
- void * (void pointer)
- int (integer)
Correct answer: 2
int (integer)
Here, compiler will ignore the pointer asterisk, when carrying a type over to multiple declarations. If we split the declarations of ptr1 and ptr2 into multiple declarations, compiler will consider them like:
int *ptr1;
int ptr2;
Thus, ptr is not int*, it is int type variable.
5) What will be the correct way to declare two integer pointers using single line declaration?
- int *ptr1,*ptr2;
- int* ptr1,ptr2;
- int * ptr1, ptr2;
- All of the above
Correct answer: 1
int *ptr1,*ptr2;
It is possible to declare multiple pointers in a single line declaration, use asterisk (*) before the pointer names.
6) Consider the following statement:
int arr[5],*ptr;
How to initialize ptr with the address of array arr?
- ptr = arr;
- ptr = &arr[0];
- ptr = &arr;
- Both 1) and 2)
Correct answer: 4
Both 1) and 2)
A pointer to an array of integers can be initialized using array name (arr) or base address of first array element (&arr[0]).
Consider the given example:
#include <stdio.h>
int main()
{
int arr[]={10,20,30};
int *ptr;
printf(" arr: %X\n",arr);
printf("&arr[0]: %X\n",&arr[0]);
//initializing ptr
ptr = arr;
printf(" ptr: %X\n",ptr);
return 0;
}
Output
arr: E34A30E0
&arr[0]: E34A30E0
ptr: E34A30E0
Here, all values are same (value of arr, value of &arr[0] and value of ptr), thus we can use both array name or address of first element of array to initialize pointer to an array.