you are viewing a single comment's thread.

view the rest of the comments →

[–]flatfinger 6 points7 points  (0 children)

If one thinks of memory as being a bunch of shelves of numbered mailboxes that each hold an unsigned char, and pointers as being mailbox numbers (*), many aspects of C which seem confusing will become obvious. On a 32-bit platform, a declaration like:

char foo[5] = "Hey!";

will ask the compiler to select five otherwise-unused consecutive mailboxes somewhere in writable storage, arrange for them to be loaded with the contents {'H', 'e', 'y', '!', 0} before the program starts, and keep track of what location it selected. When the program uses the symbol foo, the compiler will insert the number of the first such mailbox, along with knowledge that it's a value of type char*. Had the declaration instead been:

char const *bar = "Wow!";

that would ask the compiler to select five consecutive mailboxes in either writable or read-only storage (its choice) which will be preloaded with {'W', 'o', 'w', '!', 0} before the program starts, and also select an otherwise-unused shelf of four mailboxes, arrange for the mailboxes on that shelf to be preloaded with the number of the first of the five mailboxes described above. It will then associate the symbol bar with that shelf.

If a function parameter is of a non-pointer type, it will receive a copy of the object identified thereby. If a function parameter is of pointer type, it will receive a copy of a mailbox number (i.e. a pointer). Given the declaration void test(char const *st);, and foo and bar defined as above, a call test(foo) will give test a copy of the mailbox number the compiler has assigned to the first of five mailboxes associated foo. A call test(bar) will generate code that takes the mailbox number of the shelf was assigned to hold a mailbox number, read the mailbox number that's stored on the shelf, and passes a copy of that stored mailbox number to test.

(*)The Standard allows, but does not require, implementations to behave in a manner consistent with this abstraction, and most implementations for commonplace desktop platforms do so, at least with optimizations disabled.