1,483 views
3 votes
3 votes
#include<stdio.h>
int main()
{
    char arr[5][7][6];
    char *p[5][7][6];
    printf("%d\t", (unsigned)(arr+1)-(unsigned)arr);
    printf("%d", (unsigned)(p+1)-(unsigned)p);
}

Please enlighten about the 2nd printf statement. Also what is the difference between the two statements?

1 Answer

Best answer
6 votes
6 votes

This is a really bad question -- because one is not allowed to typecast and address to long because an address can be 8 bytes long and "long" unsigned be even just 2 bytes. So,  this typecast can result in loss of precision and undesired results depending on the runtime address values. This proves that this question is from some coaching material and not any standard resource. Anyway I changed "unsigned" to "unsigned long" which is also not technically correct but I'm using it to explain some other points about pointer arithmetic. You should definitely try compiling and running the parts given in PS -- those who are lazy to do can skip it.

#include<stdio.h>
int main()
{
    char arr[5][7][6];
    char *p[5][7][6];
    printf("%d\t", (unsigned long) (arr+1)-(unsigned long)arr);
    //arr+1 gives the address location arr + sizeof(*arr)
    //(unsigned)(arr+1)-(unsigned)(arr) gives the size of (*arr) 
    // = 7*6*sizeof(char) = 42 
    printf("%d", (unsigned long)(p+1)-(unsigned long)p;
    //p+1 gives the address location p + sizeof(*p)
    //(unsigned)(p+1)-(unsigned)(p) gives the size of (*p) 
    // p is an array of pointers not pointer to an array
    // So, sizeof(*p) = 7 * 6 * sizeof(char*) = 336 on 64 bit compiler
}
PS: One should try removing the "unsigned long" typecast and see the result. 
Also try changing char *p[5][7][6] to char (*p)[5][7][6];

Ref: https://gatecse.in/chapter-3-pointers/

selected by

Related questions

2 votes
2 votes
1 answer
1
Sugumaran asked Feb 7, 2018
483 views
#include<stdio.h int main() { int x=191; char *p; p=(char*)&x; printf("%d",*p); }explain it
3 votes
3 votes
1 answer
2
2 votes
2 votes
1 answer
3
Shubham Kumar Gupta asked Sep 20, 2017
379 views
Please explain the output.#include<stdio.h>int main(){ int c; printf("geeks for %ngeeks ", &c); printf("%d", c); getchar(); return 0;}
5 votes
5 votes
3 answers
4
suvasish pal asked Aug 26, 2017
604 views
Will it result in to an error if a header file is included twice?[A].Yes[B].No[C].It is compiler dependent