Sunday, January 15, 2012

Character array & Character pointer

Question 1:
char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;
What is the output ?


Question 2:



#include<stdio.h>
 
int main()
{
  char arr[] = "geeks\0 for geeks";
  char *str = "geeks\0 for geeks";
  printf ("arr = %s, sizeof(arr) = %d \n", arr, sizeof(arr));
  printf ("str = %s, sizeof(str) = %d", str, sizeof(str));
  getchar();
  return 0;
}

Output:
  arr = geeks, sizeof(arr) = 17
  str = geeks, sizeof(str) = 4
Let us first talk about first output “arr = geeks”. When %s is used to print a string, printf starts from the first character at given address and keeps printing characters until it sees a string termination character, so we get “arr = geeks” as there is a \0 after geeks in arr[].
Now let us talk about output “sizeof(arr) = 17″. When a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\0′ ,that is why size of arr is 17.
Explanation for printing “str = geeks” is same as printing “arr = geeks”. Talking about value of sizeof(str), str is just a pointer (not array), so we get size of a pointer as output.

1 comment:

  1. p now has the base address of string "GATE2011"
    p[3] is 'E' and p[1] is 'A'.
    p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4
    So the expression p + p[3] - p[1] becomes p + 4 which is base address of string "2011"

    ReplyDelete