Sunday, 25 August 2013

What is dereferencing in c ???

The term dereferencing in c means accessing the data in a memory location pointed to by a pointer.

Why can't we use “%d” in C language instead of “%u” with pointers?

  • %d will show a negative value for addresses with the most significant bit set (high addresses)
  • %u will always show the positive interpretation of the bits
  • %p is the best, since it's explicitly reserved for printing addresses.
Consider this, supposing an address of 0xffffffff.
#include <stdio.h>

int main () {
    void* val = 0xffffffff;

    printf("d = %d\n", val);
    printf("u = %u\n", val);
    printf("p = %p\n", val);

    return 0;
}
And, it's output:
d = -1
u = 4294967295
p = 0xffffffff

Friday, 23 August 2013

What's the difference between passing by reference vs. passing by value?

Best explanation I ever heard of this.
Say I want to share a web page with you.
If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.
If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.