0

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.

5
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by grumpier
Featured Replies
  • [URL="http://www.daniweb.com/search/search.php?q=pointer+tutorial"]Seek and thou shalt find.[/URL] >>How do we know the type the pointer points? You have to declare the data type when the pointer is created. [icode]int* iPointer;[/icode] >>Is it compiler specific? No. Pointers are defined by C and C++ standards, so all compilers comply. Read More

0

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?

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.