March 24, 2005 Pointers? What is the use? | ||||
---|---|---|---|---|
| ||||
Pointers point to an address in memory. You can store data in them like standard variables. You can use the address or the actual data contained at the address.. my questions is, what do they let you do that is so great? I'm not sure at all what the added value is. I am very inexperienced as a programmer(obviously), so I was wondering if someone could explain it to me and/or show me an example or two (my book shows me how to use them and talks about how they are great and so on, but not really why they are great or how they would be used to make them great.)
Confused in Spokane....
--
Marcus Koontz
ikea_the_sofa _A T_ hotmail.com
“Be the change you want to see in the world”
|
April 01, 2005 Re: Pointers? What is the use? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcus IkeaTheSofa | Hello,
Marcus IkeaTheSofa wrote...
> Pointers point to an address in memory. You can store data in them like standard variables. You can use the address or the actual data contained at the address.. my questions is, what do they let you do that is so great? I'm not sure at all what the added value is. I am very inexperienced as a programmer(obviously), so I was wondering if someone could explain it to me and/or show me an example or two (my book shows me how to use them and talks about how they are great and so on, but not really why they are great or how they would be used to make them great.)
Pointers are of great value when you have dynamic data structures such as lists or trees. You can allocate memory and store the address of the allocated memory area in a pointer. Here is a short example of a list:
typedef int DATA;
struct LIST_ELEMENT {
LIST_ELEMENT *next; // next is a pointer!
DATA data; // some data to store
};
LIST_ELEMENT *first=0; // pointer to first Element
LIST_ELEMENT *last=0; // pointer to last Element
void AppendData(DATA some_data)
{
// memory area is allocated by new, the address is store
// in 'new_element'
LIST_ELEMENT *new_element = new LIST_ELEMENT;
// fill in Data and initialize next
new_element->data = some_data;
new_element->next = 0;
// now link in Element
if(first == 0) {
// List is empty
first = new_element;
}
else {
// list contains at least 1 Element
// add new_element to the end
last->next = new_element;
}
// make last point to last element
// which is new_element
last = new_element;
}//end AppendData
// traversing is easy now
void PrintAll()
{
for(LIST_ELEMENT *rpt=first; rpt!=0; rpt=rpt->next) {
printf("val is %d\n", rpt->data);
}
}//end PrintAll
Lists are a classic example of dynamic data structures and should be included in most books that cover C and C++
HTH,
Heinz
|
Copyright © 1999-2021 by the D Language Foundation