Pointer interview questions

Question 1:



  What is a NULL pointer?
  Simply NULL pointer points to nowhere..

#include <stdlib.h>

/* NULL pointer macro */
#ifndef NULL_PTR
#define NULL_PTR (0)
#endif


int main()
{
    int i = 0; /* A pointer to integer */
    int *p2intNum = NULL_PTR;
    /* Now p2intNum points to nowhere and it could not be accessible (*p2intNum) could not accessible */
    printf("Address of p2intNum = %d ,p2intNum = %d \n",&p2intNum,p2intNum);
    /* Now allocate memory for that ptr and disply */
    p2intNum = (int *)malloc(10);
    for(i = 0; i < 10 ; i++)
    {
        printf("p2intNum[%d] = %d \n",i,*(++p2intNum));
    }
    free(p2intNum);
    return (getchar());
}
Question 2:
Explain about constant pointer and pointer to constant ? 
 const pointer / pointer to const  
 constant pointer:   
 Example:   
       const *int ptr;
      Constant pointer means that only the value is changeable but not the pointer.
  pointer to constant
   Example:
   const int *ptr;
        Pointer to constant means that only the pointer is modifiable but not the value which points to

//const pointer
void constPtr(int num)
{
    int* const ptr = &num;
    int *PtrAnother;
    int number=1000;
    printf("(ConstanctPointer):Before:The num value is:%d\n",*ptr);
    *ptr = number;
//ptr=PtrAnother; <- error :(you can change the value but not the pointer)
    printf("(ConstanctPointer):After :The num value is:%d\n",*ptr);
}
//pointer to a const
void pointer2const(int num)
{
    const int *ptr = &num;
    int *PtrAnother;
    int number=1000;
    PtrAnother=&number;
    printf("(Pointer2Constant):Before:The num value is:%d\n",*ptr);
//*ptr = 5; <- error (you can change ptr but not the value)
    ptr=PtrAnother;
    printf("(Pointer2Constant):After :The num value is:%d\n",*ptr);
}
Question 3:
What are function pointers ?
Answer
Like any other pointer type , we can able to define pointers to functions that can be assigned,placed in arrays,passed to functions,returned by functions etc.

Pointer types:

int *ptr   // pointer to an integer
float *ptr // pointer to float value
char *ptr  // pointer to char
int (*ptr)(int *)
/* ptr is a pointer to function that has int * as an argument and returns an integer */

No comments: