Fun encounter with pointers
The language C has always been a fun to learn for me. Even with its arguably small size, it has potential to dread developers with its language semantics and high dependence on machine architecture, making people specially new programmers thinking dogmatic ideologies about it.
However, the intricacies of C constructs always excite me. With the excitement of finding and learning more such little adventures, I decided to write a post whenever I found something relevant to be shared.
Note- I will not describe the problem in extreme detail. I hope reader is familiar with the language.
Behavior of C when pointer points to array.
char (*ptr); // pointer to array
ptr = &arr ; // omitting ‘&’ will generate compiler warning
// Printing 2nd character of the array
printf(“%c”,*( (*ptr)+1 ));
printf(“%c”,*(ptr + 1));
Compiling the executing the above two statements gave results I did not expect at first.
1st statement would print the 2nd character of the string “Fork” but 2nd statement would have undefined value.The reason is that ptr is a pointer to array so it needs to be first dereferenced in order to fetch 2nd character of the string.
Whereas in 2nd statement, *(ptr + 1) would jump whole array instead of single character and would give value depending on the machine.