Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Can't wrap my head around POINTERS!!!!!!
New Posts  All Forums:Forum Nav:

Can't wrap my head around POINTERS!!!!!! - Page 2

post #11 of 26
In the example I gave, reading and writing (access) to a simple int is at least twice as fast on the stack than the heap. Moving the stack pointer around is also fast.

The allocation and deallocation also takes longer on the heap as it has to find space (not always a contiguous block of memory) and dispose of it afterwards whereas if it is on the stack, the stack frame is already the correct size, it has a contiguous block of memory and disposing of it is also done quickly as the entire stack frame is popped when the function returns.

As I said, there are quite a few reasons to use the stack where possible. These were just off the top of my head

Probably the best way to see exactly what goes on is to preprocess and compile as far as assembly (don't assemble into object code or link) and compare the same operations done on the stack and the heap.
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
post #12 of 26
Thread Starter 
for sake of this app, data stacks aren't needed yet...

So the heap is just fine...

the static variables are code that my teacher put in the code and can't be changed. The things i should focus on is the code in the case statement in the int main...

so this code:...

Code:
 static const char    *PROMPT = "> ";            // prompt string for command input
static const char    PROMPT_END = ':';        // character for terminating food parameter label input

static Food        **foods;        // dynamically allocated array for storing foods
static int        nFoods = 0;        // how many foods we are storing in the array
... Can't be changed.

This case statment:...

Code:
for (;;) {
        char    cmdChar;
        float   tempVar;
        Food *tempPointer;

        cout << PROMPT;
        cin >> cmdChar;
        switch (cmdChar) {
            case 'a': case 'A':
                tempPointer = new Food;
                cout << "caloires" << endl;
                cin >> tempVar;
                tempPointer->setCaloriesValue(tempVar);
                cout << "carbohydrates" << endl;
                cin >> tempVar;
                tempPointer->setCarbsValue(tempVar);
                cout << "fat" << endl;
                cin >> tempVar;
                tempPointer->setFatValue(tempVar);
                cout << "cholesterol" << endl;
                cin >> tempVar;
                tempPointer->setCholesterolValue(tempVar);
                cout << "sodium" << endl;
                cin >> tempVar;
                tempPointer->setSodiumValue(tempVar);
                cout << "protein" << endl;
                cin >> tempVar;
                tempPointer->setProteinVar(tempVar);

                foods[nFoods] = tempPointer;
                ++nFoods;
                break;
            case 'c': case 'C':
                // code for clearing the array
                break;
            case 'd': case 'D': {
                // code for deleting a food
                }
            case 'l': case 'L':
                // code for listing the foods
                break;
            case 'q': case 'Q':
                goto quit;
            default:
                cout << "invalid command!n";
                break;
            }
        cout << endl;
        }
... is what i need to focus on. I rote some stuff for the first case, which i know works. I verified it with other classmates, and the teacher...

The things i need help with is how to use the pointers in loops to clear the array, and some how identify individual array elements, so i can remove only a single element, and then 'scoot' over the array elements on the right, over to the right side, to fill in the hole...

I do need to come up with some code that outputs each element of the array, which is the all the 'calories, fat, etc', of a specific food, like 'chicken' Then after i figure out how to output the array, i need to dump it into a file, then figure out how to 'load' or 'fin' the content from the text file, into the app and have the data correctly inject into what it represented in the original output...
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
post #13 of 26
Quote:
Originally Posted by JoBlo69 View Post
for sake of this app, data stacks aren't needed yet...

So the heap is just fine...
I don't think you have quite understood what the stack and heap are. The stack is the main place that data is stored and is a lot simpler. When you use
Code:
static Food **foods;
that pointer is on the stack. It is up to you whether that pointer should point to the stack or the heap for the data that it points to. I am not talking about the abstract data structure "stack" (that is like a first in last out queue).

This main data store is called the stack because every time you call a function, that function's stack frame is pushed on to the stack with enough storage space inside it to store all of that function's local variables. When the function returns, that stack frame is taken off. This is why you cannot return a pointer to a local variable from a function, as when the function returns the stack frame is popped off and the pointer then points to nowhere (but you can pass pointers into the function and tell the function to write to them, return pointers to the heap as that does not clean itself, pass references (in C++ only), modify global variables or return data by value.

You use the stack all the time without thinking about it. This example is on the stack and is much simpler, safer and faster:
Code:
int i;
i = 4;
cout << i
This example is on the heap, which can store larger data
Code:
int* i; // Using the heap always gives you a pointer on the stack to the data anyway
i = new int;
*i = 4;
cout << *i;
delete i; // required to avoid memory leak
That being said, if you really really do want to use the heap, there is nothing stopping you (other than common sense).

Looping through your food** is done the same either way. I hope if you see this loop you will realise how to read and write to its values (to print them out, allocate, deallocate etc as you have said you need to be able to do those)
Code:
for i = 0; i < nFoods; i++)
{
  Food* myfood = foods[i];
  cout << myfood->protein;
}
Note that if you use a new Food[] to allocate the array, you will need to use delete[] to delete the array before the program terminates. Note also that if you use new Food in your loop to allocate each of the individual food elements, you will need to loop through the entire array deleting each one. This is all extra hassle that could easily be avoided by not using the heap (just never use malloc() or "new" and it won't use the heap)

For example if you really have to use the heap (try not to first) then you allocate with
Code:
nFoods = 100;
foods = new Food[nFoods];
for(int i = 0; i < nFoods; i++)
  foods[i] = new Food;
and you MUST guarantee to clean it up properly yourself before the program exits, even if the program crashes or errors, like this
Code:
for(int i = 0; i < nFoods; i++)
  delete foods[i];
delete[] foods;
If you need to remove a specific element, remember to delete it before overwriting its pointer with a pointer from a different address, or you will get memory leak.
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
post #14 of 26
Thread Starter 
Super killer info. Thanks So much!!

I've been up all night reading up on this stuff, and i did kinda think that i had the wrong idea about the stack and the heap. Your post cleared this up for me.

Looking at that for loop, I'm trying to envision the code needed to output the data to a file. This same file has to be used to input the data back into the app. This method is to be used as a sort of save feature to this program. So what im thinking, is that when i 'output' a value to a file, i don't need or want the associated explanation of what that data represents in the file, because that file is to be used to re-inut the info back into the app as a save file, the suer doesn't need to know what the data is in the file, until after its loaded in the app.

So what i am thinking, is for each food entry, there are sevral different values that the user needs to input, like calories, fat, etc. I could just output the values in the order received by the app, and then that same file's value would get loaded back into the app in the same order. Hence the identifying description of what the data is is not required. I'm i on the right page with this??

The part where i need to remove only one element of the array (one food element, like say 'chicken') Im not sure how to do this part. I can't seem to figure out how the array elements are kept in track. Like when the user enters the food 'chicken' to be deleted, how do i associate chicken to the array numbered element?? And once i poke a hole in the array, i need to scoot over the other elements. This will change the location of the higher numbered elements, so i will need to dynamically access the array elements. I have no idea... The book we use for class isn't real helpful when it comes to re-araging array elements or in that fact, it doesn't really explain how to manipulate them other than declaring them, and deleting them.

Been trying to find an online guide for this specific topic, but haven't been able to find much of anything regarding moving the array elements around, or deleting only one element....
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
post #15 of 26
You probably want to consider a slightly structured file such as whitespace (one or more tabs, spaces etc) or comma separated values and one line per entry or one file per entry.

This would look something like
Code:
chicken,2,6,3
sausage roll,9,2,1
As it is C++, you can use any output stream just as easily as you do the standard output stream (cout) so once you have an ofstream you can just use << on it to write to it and >> to read. You may also need to use seek() to move the cursor around (for example rather than closing the file and reopening it, you can just seek back to the start, or you can seek forward 10 bytes to skip over a section or whatever)

Generally it will be easier to just have some save function that overwrites the file and just writes all of the data from the start to the end again, rather than overwriting certain lines. This can then close the stream when it is done and it will just be reopenned when you next save. You can do a similar thing for load() too.

In order to delete the element associated with "chicken" you would need to loop through all of the elements. When you find one with a name of "chicken", delete it then as you continue through the loop, replace the pointers with the pointer from the previous element and set the last pointer to NULL or a new Food. Alternatively you could just delete it and create a new Food to replace it, or provide some method of Food that empties its member data then just call chicken->delete(). This would leave you with empty spaces in the array. You may also want to keep a size variable separate from the capacity variable so that, for example, you can have an array with a capacity of 100 foods but only 2 actually being used. If you do this you would need to shunt the elements across so that when you remove elements, only the first n elements are used. I couldn't tell if nFoods was supposed to be size or capacity. My earlier examples assumed capacity but i think that it might be nFoods for size and the constant value 100 for capacity.

STL has a lot of data structures that do this kind of thing for you like linked lists, vectors and hashtables, but if you are limited to using Food**, you unfortunately cannot use any of them.
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
post #16 of 26
Thread Starter 
ok, here is what i have going. I'm getting compilation errors...

This case loops through the whole foods array, and deletes each array element. Or al least that is what it is supposed to do...

Code:
case 'c': case 'C':
                for (i = 0; i < nFoods; i++)
                {
                    delete nfoods[];
                    nfoods++;
                }
                break;
This case is supposed to ask for what food element to delete, via the food name associated to the array element. Not sure how to do this. I also have no clue on how to move the other array elements over, so there are no holes in the array...

Code:
case 'd': case 'D': {
                for (i = 0; i < nFoods; i++)
                {
                    cout << "please enter the food you with to delete:" << endl;
                    cin >> //What variable to i use to capture the inputted text? How do i associate this 'word' to the array number location??
                }
This case outputs the contents of the array elements. I'm thinking that there should be some check to see if the array element has data inside it or not, then decide to output the contents. Again, I'm not real sure what to do here...

Code:
case 'l': case 'L':
                for (i = 0; i <= 100; i++)
                {
                    cout << foods[i] << endl;
                    nfoods++;
                }
                break;
A link to some example code somewhere out in the internet, that is related to what I'm trying to do, or some homemade example code would help a lot. I think i have enough idea on what needs to be done, but the code needed to do this, i can seem to figure out...
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
post #17 of 26
Thread Starter 
I'm still flappin' in the breeze here... Anyone have a good link to what I'm trying to do??
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
post #18 of 26
Quote:
Originally Posted by JoBlo69 View Post
ok, here is what i have going. I'm getting compilation errors...

Code:
delete nfoods[];
nfoods++;
delete deletes a single value from the heap that was allocated with new foo. delete[] deletes an array that was allocated with new foo[]. nFoods is a value on the stack that gives either the size or capacity of the array. nfoods[] is a syntax error and you cannot delete nfoods if it not on the heap anyway. You have not actually said what nfoods is here, nFoods was specified in an earlier post (note the capital F)

You may have other errors as well but this is a good place to start.

My example shows how to loop through the array deleting all of the elements that were allocated to the heap, and then how to delete the array of pointers that is also on the heap.
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
post #19 of 26
Thread Starter 
Code:
for i = 0; i < nFoods; i++)
{
  Food* myfood = foods[i];
  cout << myfood->protein;
}
i see... This is going to take some coding to get this to delete everything...

I'm off to bed, and I'll post some code here in a few hours...

I noticed the time change we have going on here in our conversation, so you may not see a reply until this time tomorrow. roughly 4am my time.

Thanks for the help.
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
good enough
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6600 3ghz Gigabyte GA-EP45-DS3L 9800GT 2x2gb fatility DDR2 1066 
Hard DriveOSMonitorMouse
2 x 74gb raptor raid0 win7 64bit Samsung 245BW Razer 3G diamondback 
Mouse Pad
glass core pad 
  hide details  
Reply
post #20 of 26
Quote:
Originally Posted by ghell View Post
Code:
for(int i = 0; i < nFoods; i++)
  delete foods[i];
delete[] foods;
I have already given you the code to delete everything.

This loops through and deletes each individual element (that was allocated on the heap with new Food) then at the end deletes the array of Foods that was on the heap (that was allocated with new Food[])
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
Serene Power
(13 items)
 
  
CPUMotherboardGraphicsRAM
Dual Xeon E5620 Supermicro X8DAL-i EVGA 570HD SC 8GiB Corsair DDR3 1333 ECC-R 
Hard DriveOptical DriveOSMonitor
OCZ Agility 3 120GB SSD (+16TB NAS) LG 10x Blu-Ray Windows 7 x64 / Debian x64 Dell 2408WFP, P2411H 
PowerCase
850W CoolerMaster SilentPro M CoolerMaster Cosmos Pure 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Can't wrap my head around POINTERS!!!!!!