Newbie Question
What is the difference between the followings?
It would be quiet helpful if you could also give me basics of how each are represented in memory?
char [10];
char *p;
const char *p;
char * const P;
Thanks in advance
Manav
[262 byte] By [
debkumar] at [2007-11-11 7:26:31]

# 1 Re: Newbie Question
I find your char [10] a little confusing, but I'll be broad in my explanation:
I assume you are asking about the 10th element of a character array (or perhaps you're declararing an array of 10 chars). Arrays are contiguous areas of memory of size ( number of elements * "size" of each element). The size of the element is determined by the memory set aside to store an item of the data type of the element. So, an array of 10 chars would be 10 bytes of contiguous memory.
We access an array through the memory location of the first element of the array - the array name is an abstraction for that memory location. Because the memory is contiguous, and that each element uses the data type's size, then the second element of the char array is found at the memory location one byte above the start, the third element is two bytes above, etc. So the 10th element of a char array is found at the memory location 9 bytes above the address of the first element. The compiler does this memory location addition for us.
Pointers: the other three items in your list are all pointers. Pointers are memory locations which hold a memory address which gives us access to the item of interest. The data type tells us the size of the item of interest - how much memory we are going to have to deal with if we follow the pointer to the item of interest. It is my understanding that the "const" keyword does not change the manner in which a pointer is stored in memory, or what it stores, but has to do with the attribute of mutability of either the object being pointed to or the pointer itself. [depending on if it is a const pointer or a pointer to a const item/object]
nspils at 2007-11-11 21:02:22 >

# 3 Re: Newbie Question
char p[10] allocates 10 chars in the program's memory space. You can use it now.
char *p allocates an 'integer' called a pointer that can store an address in it. This address is garbage until you assign the pointer with new, address of (&) or similar operation. When you use new, you ask the OS to allocate you some of the computer's memory. If you use & or assignment of an array name, etc, you are just pointing to memory you already own and its ok. Pointers are used when the memory required is very large, unknown in size, required for a data structure(list, tree), and other reasons.
jonnin at 2007-11-11 21:04:17 >
