Thursday 3 July 2014

Constant pointer Vs a pointer to a constant.


int * const ptr —> ptr is constant pointer. You can change the value at the location pointed by pointer p, but you can not change p to point to other location. int const * ptr —> ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot change the value pointed by ptr.


int * const ptr :

int main()
{
    int x = 5;
    int * const ptr = &x;
    ++(*ptr);
    printf("%d", x);
   
    return 0;
}
Output : 6

above program works well because we have a constant pointer and we are not changing ptr to point to any other location. We are only icrementing value pointed by ptr



int const * ptr

int main()
{
    int x = 5;
    int const * ptr = &x;
    ++(*ptr);
    printf("%d", x);
   
    return 0;
}

Output: Compiler Error

In the above program, ptr is a pointer to a constant. So the value pointed cannot be changed


#include<stdio.h>
int main()
{
  typedef static int *i;
  int j;
  i a = &j;
  printf("%d", *a);
  return 0;
}
(A) Runtime Error
(B) 0
(C) Garbage Value
(D) Compiler Error


Answer: (D)

Explanation: Compiler Error -> Multiple Storage classes for a. In C, typedef is considered as a storage class. The Error message may be different on different compilers

No comments:

Post a Comment