i am confused by pointers. How do we know the type the pointer points? Is it compiler specific? how do we implement delete[]? Are there any books or articles about this topic? Wait for your replies.

Recommended Answers

All 6 Replies

Seek and thou shalt find.

>>How do we know the type the pointer points?
You have to declare the data type when the pointer is created. int* iPointer; >>Is it compiler specific?
No. Pointers are defined by C and C++ standards, so all compilers comply.

commented: :) +4
commented: Though I know it's not your style, it would've been funnier if you said "GIYF" =P +4

Here's a silly little illustration I drew just now:

commented: Nice picture =) +4

when we use int *p=new int; we know p point to int. But i just wanna know how the compiler know p's type? When we delete a pointer to a array, how the compiler know how many bytes to release?

when we use int *p=new int; we know p point to int. But i just wanna know how the compiler know p's type?

Because you've told it so. int *p tells the compiler that p is a pointer to int. The compiler also knows that the expression "new int" yields a value of type pointer to int, that can stored in the pointer p.

If you want a self-respecting compiler to complain bitterly, tell it "int *p = new double;" : it recognises that "new double" does not yield a pointer to int, and complains about a mismatch of types.

When we delete a pointer to a array, how the compiler know how many bytes to release?

The compiler doesn't. All the compiler knows is that it's asked to delete an array (as in "delete [] whatever;") because the [] tells it that.

When dynamically allocating an array, you specifically tell it how many elements to allocate. There is nothing stopping code that manages memory allocation from keeping track of things, and retrieving the value when working with the delete operator. The methods of doing that, however, vary between compilers. And there is no portable way for your code to retrieve that value (unless you also keep track of such things yourself).

Oh; another tutorial on pointers is here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.