Question

I have a couple of confusions regarding pointers.

I am putting all of them in the form of question.

1) How does compiler handle various pointers?
2) How does a compiler figure out the data type of pointers passed at compile time?

All I know, pointers are stored in the memory in the form of an Unsigned Integer which is used to hold the base address of the object that it is pointing.
Now, is it the Symbol Table that plays the key role?

Was it helpful?

Solution

Maybe a concrete example would help. Try this:

#include <stdio.h>

const double step_size = 5.0; // degrees of arc

struct Location {
    double latitude;
    double longitude;
};

void go_north(struct Location *const loc) {
    loc->latitude += step_size;
}

int main() {
    struct Location there;
    there.latitude  =   41.0;
    there.longitude = -101.5;
    go_north(&there);
    printf("Lat. %6.1f, long. %6.1f.\n", there.latitude, there.longitude);
    return 0;
}

How does the compiler know that the address *go_north()* receives is the address of a struct Location? Answer: the programmer has said so, by writing the function control *void go_north(struct Location *const loc).*

Regarding your comment on lexical analysis, believe it or not, the linker does not need to know anything about the size or layout of an object pointed to, even if pointers to such objects are passed around between various *.o objects. This is why header files are used: so that the pre-link compiler proper knows the layout at pre-linking compile time. A lot of strange things can go in a symbol table in special circumstances, so I'll not be so bold as to assert, categorically, that no symbol table ever contains the information you suggest; but in normal usage the symbol table omits the information, because the linker does not need it.

One suspects that this does not altogether answer your question, but the example might help to focus the question to make it specific enough that it can be answered. So, if a concrete example helps, plus this partial answer, here they are.

(If you happen to be on a Linux platform, you might find the readelf command very interesting.)

OTHER TIPS

1) How does compiler handle various pointers?

They are handled as memory addresses. Usually 16 or 32 or 64 bit unsigned integer.

2) How does a compiler figure out the data type of pointers passed at runtime?

The C-compiler doesn't figure out any data types at the runtime. Pointer types are figured out at the compile time. At runtime the pointers are just stupid memory addresses pointing to unknown types.

There is no feature built into the C language for figuring out the type of a pointer at run time. You always know the type at compile time.

void(char * x)
{
  // x points to a char
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top