Thursday, February 23, 2012

(contd...) Top 50 Interview Questions & Answers in C Programming

CHAPTER 4: Pointers

1. What is a pointer in C?

A pointer is a special variable in C language meant just to store address of any other variable or function. Pointer variables unlike ordinary variables cannot be operated with all the arithmetic operations such as '*','%' operators.
 
It follows a special arithmetic called as pointer arithmetic.
 
A pointer is declared as:
 
int *ap;
int a = 5;
 
In the above two statements an integer a was declared and initialized to 5. A pointer to an integer with name ap was declared.
 
Next before ap is used
ap=&a;
 
This operation would initialize the declared pointer to int. The pointer ap is now said to point to a.
 
Operations on a pointer:

Dereferencing operator ' * ': This operator gives the value at the address pointed by the pointer . For
example after the above C statements if we give printf("%d",*ap);

Actual value of a that is 5 would be printed. That is because ap points to a.

Addition operator ' + ': Pointer arithmetic is different from ordinary arithmetic.

ap=ap+1;
 
Above expression would not increment the value of ap by one, but would increment it by the number of
bytes of the data type it is pointing to. Here ap is pointing to an integer variable hence ap is incremented
by 2 or 4 bytes depending upon the compiler.
 
2. What are the advantages of using pointers?

Pointers are special variables which store address of some other variables.
Syntax: datatype *ptr;
 
Here * indicates that ptr is a pointer variable which represents value stored at a particular address.
Example: int *p;
 
'p' is a pointer variable pointing to address location where an integer type is stored.
 
Advantages:

1. Pointers allow us to pass values to functions using call by reference. This is useful when large sized
arrays are passed as arguments to functions. A function can return more than one value by using call by
reference.

2. Dynamic allocation of memory is possible with the help of pointers.

3. We can resize data structures. For instance, if an array's memory is fixed, it cannot be resized. But in
case of an array whose memory is created out of malloc can be resized.

4. Pointers point to physical memory and allow quicker access to data.

3. What are the differences between malloc() and calloc()?

Allocation of memory at the time of execution is called dynamic memory allocation. It is done using the standard library functions malloc() and calloc(). It is defined in "stdlib.h". 

malloc(): used to allocate required number of bytes in memory at runtime. It takes one argument, viz. size in bytes to be allocated.
 
Syntax:

void * malloc(size_t size);
 
Example:

a = (int*) malloc(4);
4 is the size (in bytes) of memory to be allocated.
calloc(): used to allocate required number of bytes in memory at runtime. It needs two arguments viz.,

1. total number of data and
2. size of each data.

Syntax:
 
void * calloc(size_t nmemb, size_t size);
 
Example:
 
a = (int*) calloc(8, sizeof(int));

Here sizeof indicates the size of the data type and 8 indicates that we want to reserve space for storing 8
integers.
 
Differences between malloc() and calloc() are:

1. Number of arguments differ.
2. By default, memory allocated by malloc() contains garbage values. Whereas memory allocated by calloc() contains all zeros.

4. How to use realloc() to dynamically increase size of an already allocated array?

realloc(): This function is used to increase or decrease the size of any dynamic memory which is allocated using malloc() or calloc() functions.
 
Syntax: 

void *realloc(void *ptr, size_t newsize);

The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc functions. The second argument 'newsize' is the size in bytes, of a new memory region to be allocated by realloc. This value can be larger or smaller than the previously allocated memory. The realloc function adjusts the old memory region if newsize is smaller than the size of old memory.
If the newsize is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region. The function then deallocates the old memory region. realloc function is helpful in managing a dynamic array whose size may change during execution.
 
Example:  

A program that reads input from standard input may not know the size of data in advance. In this case,
dynamically allocated array can be used so that it is possible allocate the exact amount of memory using realloc function.

5. What is the equivalent pointer expression for referring an element a[i][j][k][l], in a four
dimensional array?

 
Consider a multidimensional array a[w][x][y][z].
 
In this array, a[i] gives address of a[i][0][0][0] and a[i]+j gives the address of a[i][j][0][0] Similarly, 
a[i][j] gives address of a[i][j][0][0] and a[i][j]+k gives the address of a[i][j][k][0]
 
a[i][j][k] gives address of a[i][j][k][0] and a[i][j][k]+l gives address of a[i][j][k][l]
 
Hence a[i][j][k][l] can be accessed using pointers as *(a[i][j][k]+l)
where * stands for value at address and a[i][j][k]+l gives the address location of a[i][j][k][l].
 
Program: 

Example program to illustrate pointer denotation of multi-dimensional arrays.
 
#include<stdio.h>
#include<string.h>
int main() {
int a[3][3][3][3]; //it gives address of a[0][0][0][0] .
printf(" \n address of array a is %u", a);
printf("\n address of a[2][0][0][0] is %u ,given by a[2], %u given by a+2", a[2], a + 2);
printf("\n address of a[2][2][0][0] is %u ,given by a[2][2], %u given by a[2]+2", a[2][2], a[2] + 2);
printf("\n address of a[2][2][1][0] is %u ,given by a[2][2][1] , %u given by a[2][2]+1", a[2][2][1], a[2][2] + 1); return 0;
}

Output:
address of array a is 65340
address of a[2][0][0][0] is 65448, given by a[2] , 65448 given by a+2
address of a[2][2][0][0] is 65484, given by a[2][2] ,65484 given by a[2]+2
address of a[2][2][1][0] is 65490, given by a[2][2][1] , 65490 given by a[2][2]+1
 
Explanation:

This output may differ from computer to computer as the address locations are not same for every computer.

6. Declare an array of three function pointers where each function receives two integers and returns float.
 
Declaration:

float (*fn[3])(int, int);
 
Program: 

Illustrates the usage of above declaration
#include<stdio.h>
float (*fn[3])(int, int);
float add(int, int);
int main()
{
int x, y, z, j;
for (j = 0; j < 3; j++)
{
fn[j] = &add;
}
x = fn[0](10, 20);
y = fn[1](100, 200);
z = fn[2](1000, 2000);
printf("sum1 is: %d \n", x);
printf("sum2 is: %d \n", y);
printf("sum3 is: %d \n", z);
return 0;
}
float add(int x, int y)
{
float f = x + y;
return f;
}
 
Output:
sum1 is: 30
sum2 is: 300
sum3 is: 3000
 
Explanation:
Here 'fn[3]' is an array of function pointers. Each element of the array can store the address of function 'float add(int, int)'.
fn[0]=fn[1]=fn[2]=&add
 
Wherever this address is encountered add(int, int) function is called.

7. Explain the variable assignment in the declaration
 
int *(*p[10])(char *, char *);
 
It is an array of function pointers that returns an integer pointer. Each function has two arguments which in turn are pointers to character type variable. p[0], p[1],....., p[9] are function pointers.

return type : integer pointer.
p[10] : array of function pointers
char * : arguments passed to the function
 
Program: 

Example program to explain function pointers.
#include<stdio.h>
#include<stdlib.h>
int *(*p[10])(char *, char *); //average function which returns pointer to integer whose value is average of ascii value of characters passed by pointers
int *average(char *, char *); //function which returns pointer to integer whose value is sum of ascii value of characters passed by pointers
int *sum(char *, char *);
int retrn;
int main(void) 
{
int i;
for (i = 0; i < 5; i++) 
{
//p[0] to p[4] are pointers to average function. 
p[i] = &(average);
}
for (i = 5; i < 10; i++) 
{
//p[5] to p[9] are pointers to sum function
p[i] = &(sum);
}
char str[10] = "vediklabs.in";
int *intstr[10];
for (i = 0; i < 9; i++) 
{
//upto p[4] average function is called, from p[5] sum is called.
 
intstr[i] = p[i](&str[i], &str[i + 1]);
if (i < 5) 
{
//prints the average of ascii of both characters
printf(" \n average of %c and %c is %d",
str[i], str[i + 1],*intstr[i]);
}
else 
{
//prints the sum of ascii of both characters.
printf(" \n sum of %c and %c is %d",
str[i], str[i + 1], *intstr[i]);
}
}
return 0;
}/
/function average is defined here
int *average(char *arg1, char *arg2) 
{
retrn = (*arg1 + *arg2) / 2;
return (&retrn);
}                                                     //function sum is defined here
int *sum(char *arg1, char *arg2) 
{
retrn = (*arg1 + *arg2);
return (&retrn);
}

Output:

average of n and o is 110
average of o and d is 105
average of d and a is 98 average of d and a is 98
average of a and l is 102
average of l and o is 109
sum of o and . is 157
sum of . and c is 145
sum of c and o is 210
sum of o and m is 220

Explanation:

In this program p[10] is an array of function pointers. First five elements of p[10] point to the function: int *average(char *arg1,char *arg2). Next five elements point to the function int *sum(char *arg1,char *arg2). They return pointer to an integer and accept pointer to char as arguments.
 
Function average:
int *average(char *arg1,char *arg2) This function finds the average of the two values of the addresses passed to it as arguments and returns address of the average value as an integer pointer.
 
Function sum:
int *sum(char *arg1,char *arg2) This function finds the sum of the two values of the addresses passed to it as arguments and returns address of the sum value as an integer pointer.
 
8. What is the value of sizeof(a) /sizeof(char *) 
in a code snippet:
char *a[4]={"sridhar","raghava","shashi","srikanth"};

 
Explanation:

Here a[4] is an array which holds the address of strings. Strings are character arrays themselves.
 
Memory required to store an address is 4 bits. So memory required to store 4 addresses is equal to 4*4=16 bits.
 
char *; is a pointer variable which stores the address of a char variable.
 
So sizeof(char *) is 4 bits. Therefore sizeof(a) /sizeof(char *) = 16/4 = 4 bytes.
 
9.
 (i) What are the differences between the C statements below:
char *str = "Hello";
char arr[] = "Hello";
(ii) Whether following statements get complied or not? Explain each statement.
arr++;
*(arr + 1) = 's';
printf("%s",arr);

(i) char *str="Hello";
"Hello" is an anonymous string present in the memory. 'str' is a pointer variable that holds the address of this string.
char arr[]="Hello";
This statement assigns space for six characters: 'H' 'e' 'l' 'l' 'o' '\0' . 'arr' is the variable name assigned to this array of characters.

str[4] and arr[4] also have different meanings.
str[4]: adds 4 to the value of 'str' and points to the address same as value of str + 4.
arr[4]: points to the fourth element in array named 'arr'.

(ii) 'arr' is variable name of an array. A variable name can not be incremented or decremented. Hence arr++ is an invalid statement and would result in a compilation error. 
*(arr+1)='s';
'arr' is the name of a character array that holds string "Hello". 
Usually, name of an array points to its base address. Hence value of arr is same as &arr[0]. 

arr+1 is address of the next element: &arr[1]

Character 's' is assigned to the second element in array 'arr', thereby string changes from "Hello" to "Hello".
printf("%s",arr );
 
This statement prints the string stored in character array 'arr'.

To be contd...

A Special Thanks to www.interviewmantra.net. for providing content and to Mr. Sridhar Jammalamadaka for their valuable guidance.

No comments:

Post a Comment