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.

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).

This article has been dead for over six months. Start a new discussion instead.