Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming

Reply
 
LinkBack Thread Tools
Old 03-08-08   #1 (permalink)
Programmer
 
JoBlo69's Avatar
 
intel nvidia

Join Date: Jan 2007
Posts: 3,363

Rep: 170 JoBlo69 is acknowledged by manyJoBlo69 is acknowledged by many
Unique Rep: 146
Trader Rating: 16
Default Can't wrap my head around POINTERS!!!!!!

i don't get it...

I mean, i understand that all a pointer is, is a 'pointer' to a memory location.

Like an address to a house. Its just a locater to let other things know where you house is.

I'm working on this assignment for school, and I'm just stuck. I bought a new book, been reading online, but still cant figure out what I'm reading to what i need to do...

Maybe I'm just over thinking it. Maybe i just don't understand it to even begin to think about using the idea. Who knows...

Here is some code i am working on....

Code:
// set up code to report memory leaks when running in Debug mode
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif

#include <iostream>
#include <iomanip>
#include "Food.h"

using namespace std;

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



int main(void)
{
    foods = new Food *[100];

    cout << "Nutricalc 1.0\nImplemented by: your name" << endl << endl;
    
    cout << "\nedit food database" << endl
         <<   "   commands: a(dd), c(lear), d(elete) index, l(ist), m(eal), q(uit)" << endl
         <<   "-------------------------------------------------------------------" << endl << endl;
    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':
                for (foods[nfoods] >= 0 ; foods[nfoods] <= 100 ; foods[nfoods]++)
                {
                    delete nfoods[];   //This case is supposed to delete all the elements of the array that the food entry's are stored in. But cant get it to work...
                    nfoods++;
                }
                break;
            case 'd': case 'D': {
                // code for deleting a food. Dont have the slightest idea...
                }
            case 'l': case 'L':
                for (nfoods[] =! null ; nfoods[] >= 100 ; nfoods[]++)
                {
                    cout << foods << endl;  //Code for outputting each food.
                    nfoods++;
                }
                break;
            case 'q': case 'Q':
                goto quit;
            default:
                cout << "invalid command!\n";
                break;
            }
        cout << endl;
        }
    
quit:
    free(Food);

    cout << endl;  // Clears the array so there is no memory leaks, but not sure what to put in for this part...

    // report any memory leaks
    #ifdef _DEBUG
        _CrtDumpMemoryLeaks();
    #endif
    
    return 0;
}
Everything in case 'A' refers to functions in a class that are in Food.h and a Food.cpp files. I know for sure this code works. I just can get the other case statements to get a grip!!!

Please Help!!!! Driving me nuts!!!

Also, i need to make a function that outputs each array element to a file. Again, not to comfortable with pointer arrays enough to figure this out...
__________________
My Lego case thread. With PICS!!!
-----------------------------------------------------------------------
Video card RMA database thread. I am working on an application that allows users to input their cards issues into a database, to build a knowledge base for what types of cards have a lower fail rate.

System: The "hold-me-over-until-i-can-get-a-i7" PC
CPU
E7200
Motherboard
Gigabyte GA-EP45-DS3L
Memory
Nothing!!! (new ram pending)
Graphics Card
8800GT
Hard Drive
2 x 74gb raptor raid0
Case
craptastic!!!
OS
64x vista ult.
Monitor
24" samsung
JoBlo69 is offline JoBlo69's Gallery   Reply With Quote
Old 03-08-08   #2 (permalink)
The Project Keeper
 
Licht's Avatar
 
amd ati

Join Date: Mar 2007
Location: Bel Air
Posts: 9,406
Blog Entries: 3

Rep: 277 Licht is a proven memberLicht is a proven memberLicht is a proven member
Unique Rep: 184
Folding Team Rank: 875
Trader Rating: 0
Default

I don't understand what your problem is. Maybe you could explain it more?

System: (AMD-AMD-ATI)-(CPU-Chip-GPU)
CPU
AMD Athlon X2 5200+
Motherboard
Gigabyte 790X AM2+
Memory
6GB Kingston DDR2 667MHZ
Graphics Card
Saphire HD 3870
Hard Drive
[RAID0] [2X] WD 160GB 7,200RPM
Sound Card
X-Fi Extreme Gamer Fatality Professional
Power Supply
OCZ Game-X-Stream 700w
Case
NZXT Black Steel
CPU cooling
Stock Heatskin & Fan
GPU cooling
Stock Saphire 3870 Cooling
OS
Windows Vista Home Premium x64 SP1
Monitor
Samsung SyncMaster 19" Widescreen
Licht is offline I fold for Overclock.net Overclocked Account Licht's Gallery   Reply With Quote
Old 03-08-08   #3 (permalink)
Programmer
 
JoBlo69's Avatar
 
intel nvidia

Join Date: Jan 2007
Posts: 3,363

Rep: 170 JoBlo69 is acknowledged by manyJoBlo69 is acknowledged by many
Unique Rep: 146
Trader Rating: 16
Default

There is a dynamic array:

Code:
 static Food **foods
foods = new Food *[100];
each element of this array contains the info from this class:

Code:
#pragma once

class Food
{    
public:
    
    void setCaloriesValue(float number);
    void setCarbsValue(float number);
    void setFatValue(float number);
    void setCholesterolValue(float number);
    void setSodiumValue(float number);
    void setProteinValue(float number);

    float returnCalories(void);
    float returnCarbs(void);
    float returnFat(void);
    float returnCholesterol(void);
    float returnSodium(void);
    float returnProtein(void);

    enum Category 
        {
            unknown = -1, meat, poultry, seafood, dairy, vegetable, 
            fruit, grain, sweet, nCategories
        };

    ~Food(void);
    
private:

    char      *name;          // name of the food 
    Category  category;       // what kind of food 
    float     calories;       // calories 
    float     carbohydrates;  // grams 
    float     fat;            // grams 
    float     cholesterol;    // grams 
    float     sodium;         // grams 
    float     protein;        // grams
};
The main thing i am having problems with, is keeping track of each array entry. I'm thinking i need to setup a temp variable to keep track of where in at in the array...

I need to setup a loop that goes through and 'deletes' each array entry. Then i need to make another loop that only deletes a specific entry, say:

foods[3] or foods[34]

Not to sure if i have the right idea here... But I'm pretty sure i have the right thinking in putting in a temp variable to keep track of where I'm at in the array....

Hope this makes more sense to you than it does for me... lol.... Not really sure if i'm on the right track...
__________________
My Lego case thread. With PICS!!!
-----------------------------------------------------------------------
Video card RMA database thread. I am working on an application that allows users to input their cards issues into a database, to build a knowledge base for what types of cards have a lower fail rate.

System: The "hold-me-over-until-i-can-get-a-i7" PC
CPU
E7200
Motherboard
Gigabyte GA-EP45-DS3L
Memory
Nothing!!! (new ram pending)
Graphics Card
8800GT
Hard Drive
2 x 74gb raptor raid0
Case
craptastic!!!
OS
64x vista ult.
Monitor
24" samsung
JoBlo69 is offline JoBlo69's Gallery   Reply With Quote
Old 03-08-08   #4 (permalink)
The Project Keeper
 
Licht's Avatar
 
amd ati

Join Date: Mar 2007
Location: Bel Air
Posts: 9,406
Blog Entries: 3

Rep: 277 Licht is a proven memberLicht is a proven memberLicht is a proven member
Unique Rep: 184
Folding Team Rank: 875
Trader Rating: 0
Default

Ok so you need a loop to clear an array. Simple enough.

In C# : (Meaning you have to convert this to C++ yourself.)

Code:
int Position
for (Position = 0; Position < (array size); Position++)
{
array[Position] = 0;
}
At least i think thats what your asking.

System: (AMD-AMD-ATI)-(CPU-Chip-GPU)
CPU
AMD Athlon X2 5200+
Motherboard
Gigabyte 790X AM2+
Memory
6GB Kingston DDR2 667MHZ
Graphics Card
Saphire HD 3870
Hard Drive
[RAID0] [2X] WD 160GB 7,200RPM
Sound Card
X-Fi Extreme Gamer Fatality Professional
Power Supply
OCZ Game-X-Stream 700w
Case
NZXT Black Steel
CPU cooling
Stock Heatskin & Fan
GPU cooling
Stock Saphire 3870 Cooling
OS
Windows Vista Home Premium x64 SP1
Monitor
Samsung SyncMaster 19" Widescreen
Licht is offline I fold for Overclock.net Overclocked Account Licht's Gallery   Reply With Quote
Old 03-08-08   #5 (permalink)
Apple Doesn't Love You
 
rabidgnome229's Avatar
 
intel nvidia

Join Date: Feb 2006
Location: Pittsburgh
Posts: 4,975
Blog Entries: 1

Rep: 564 rabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famous
Unique Rep: 338
FAQs Submitted: 6
Trader Rating: 5
Default

If you declare your array this way
Code:
 static Food **foods
foods = new Food *[100];
You're making an array of pointers to Food rather than an array of Food
__________________
BIG BROTHER
I put on my robe and wizard hat...

IS WATCHING

System: It goes to eleven
CPU
E6300
Motherboard
DS3
Memory
2GB XMS2 DDR2-800
Graphics Card
EVGA 8600GTS
Hard Drive
1.294 TB
Sound Card
Audigy 2 ZS
Power Supply
Corsair 520HX
Case
Lian-Li v1000B Plus
CPU cooling
TTBT
GPU cooling
Thermalright V2
OS
Arch Linux/XP
Monitor
Samsung 226bw
rabidgnome229 is offline Overclocked Account   Reply With Quote
Old 03-09-08   #6 (permalink)
Programmer
 
JoBlo69's Avatar
 
intel nvidia

Join Date: Jan 2007
Posts: 3,363

Rep: 170 JoBlo69 is acknowledged by manyJoBlo69 is acknowledged by many
Unique Rep: 146
Trader Rating: 16
Default

Quote:
Originally Posted by rabidgnome229 View Post
If you declare your array this way
Code:
 static Food **foods
foods = new Food *[100];
You're making an array of pointers to Food rather than an array of Food
Advice on how to fix it?? This is part of the reason why I'm not getting this pointer idea... i think...?

And the comment made about the code to delete array elements wont work the way you suggest. If you set the first array ([0]) to 0 it screws up the entire array. The first entry, the '0', also known as null is needed for the array to work correctly.... Not entirely sure why, but some friends that are way ahead of me in the coding thing said that you ether need to use a 'delete' command in the array. I'm guessing that C++ is smart enough to understand that your not deleting the array, but just the data inside the array's reference...

But like i said, i could be wrong... I'm still kinda a nub at this
__________________
My Lego case thread. With PICS!!!
-----------------------------------------------------------------------
Video card RMA database thread. I am working on an application that allows users to input their cards issues into a database, to build a knowledge base for what types of cards have a lower fail rate.

System: The "hold-me-over-until-i-can-get-a-i7" PC
CPU
E7200
Motherboard
Gigabyte GA-EP45-DS3L
Memory
Nothing!!! (new ram pending)
Graphics Card
8800GT
Hard Drive
2 x 74gb raptor raid0
Case
craptastic!!!
OS
64x vista ult.
Monitor
24" samsung
JoBlo69 is offline JoBlo69's Gallery   Reply With Quote
Old 03-09-08   #7 (permalink)
New to Overclock.net
 
intel ati

Join Date: Mar 2007
Posts: 159

Rep: 11 ghell Unknown
Unique Rep: 9
Trader Rating: 0
Default

Code:
Food foods[] = new Food[100];
Gets you a pointer to enough heap space to store 100 "Food"s, rather than their pointers. However, avoid use of the heap where possible. Always remember to use delete[] to free the heap memory or you will get memory leak.

If you use
Code:
Food foods[100]
it will create it on the stack. You then have to zero this memory yourself before use (or assign it all) but it is faster than the heap and will never lead to memory leak.

I think the source of your confusion lies in the fact that arrays in C/C++ are just pointers to a sequence of bytes. When you use an array you can use
Code:
int* myPtr = &myIntArray[0]
and it makes no difference. This is also why sometimes you see int main(int argc, char* argv[]) and sometimes you see int main(int argc, char** argv[]).
__________________
System: Anon.
CPU
Core 2 Duo E8500
Motherboard
ASUS Striker Exteme 680i
Memory
4*1024MiB Corsair XMS2 Pro 800MHz 4-4-4-12 (LEDs)
Graphics Card
HD 4870x2
Hard Drive
2*250GB Seagate Barracuda 7200.10, 1*500GB 7200.11
Sound Card
X-Fi XtremeMusic
Power Supply
1000W Enermax Galaxy DXX
Case
SilverStone Temjin TJ07
CPU cooling
D-Tek Fuzion
OS
Vista Ultimate x64 / Debian x64
Monitor
Dell 2408WFP (DisplayPort)

Last edited by ghell : 03-09-08 at 09:48 PM.
ghell is offline   Reply With Quote
Old 03-09-08   #8 (permalink)
Apple Doesn't Love You
 
rabidgnome229's Avatar
 
intel nvidia

Join Date: Feb 2006
Location: Pittsburgh
Posts: 4,975
Blog Entries: 1

Rep: 564 rabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famous
Unique Rep: 338
FAQs Submitted: 6
Trader Rating: 5
Default

Quote:
Originally Posted by ghell View Post
If you use
Code:
Food foods[100]
it will create it on the stack. You then have to zero this memory yourself before use (or assign it all) but it is faster than the heap and will never lead to memory leak.
I've never heard that. Why do you say the stack is faster than the heap? The only reason I could really think of is page faults, but that shouldn't affect a trivial program like this
__________________
BIG BROTHER
I put on my robe and wizard hat...

IS WATCHING

System: It goes to eleven
CPU
E6300
Motherboard
DS3
Memory
2GB XMS2 DDR2-800
Graphics Card
EVGA 8600GTS
Hard Drive
1.294 TB
Sound Card
Audigy 2 ZS
Power Supply
Corsair 520HX
Case
Lian-Li v1000B Plus
CPU cooling
TTBT
GPU cooling
Thermalright V2
OS
Arch Linux/XP
Monitor
Samsung 226bw
rabidgnome229 is offline Overclocked Account   Reply With Quote
Old 03-09-08   #9 (permalink)
New to Overclock.net
 
intel ati

Join Date: Mar 2007
Posts: 159

Rep: 11 ghell Unknown
Unique Rep: 9
Trader Rating: 0
Default

Quote:
Originally Posted by rabidgnome229 View Post
Why do you say the stack is faster than the heap?
Because it is faster. For a trivial program, it will not make a noticeable impact on performance anyway but for a large application or an application that involves a lot of number crunching on small data sets, the stack should be used. Using the heap unnecessarily will inevitably lead to memory leak anyway.

The simplest example of the heap being slower is that every time you read or write to the heap, you have to go through a pointer. Imagine the trivial case of storing a 32 bit integer on the stack vs storing a pointer to it on the heap. In order to read the integer from the stack, you can just read it directly into a register. In order to read it form the heap you must get the pointer into a register, go and find it on the heap and then get the value. When writing back you must do the same thing. This is just a small example that should hopefully be simple enough to see instantly without having to think about it but there are further causes of lower performance on the heap. You should be able to find plenty of information on these further details if you google phrases such as "stack faster than heap" or "stack vs heap".

The heap should mainly just be used where large amounts of data need to be used, such as when loading images. This is because the stack is a very small store in comparison.

The stack is also simpler so why overcomplicate things?
__________________
System: Anon.
CPU
Core 2 Duo E8500
Motherboard
ASUS Striker Exteme 680i
Memory
4*1024MiB Corsair XMS2 Pro 800MHz 4-4-4-12 (LEDs)
Graphics Card
HD 4870x2
Hard Drive
2*250GB Seagate Barracuda 7200.10, 1*500GB 7200.11
Sound Card
X-Fi XtremeMusic
Power Supply
1000W Enermax Galaxy DXX
Case
SilverStone Temjin TJ07
CPU cooling
D-Tek Fuzion
OS
Vista Ultimate x64 / Debian x64
Monitor
Dell 2408WFP (DisplayPort)
ghell is offline   Reply With Quote
Old 03-09-08   #10 (permalink)
Apple Doesn't Love You
 
rabidgnome229's Avatar
 
intel nvidia

Join Date: Feb 2006
Location: Pittsburgh
Posts: 4,975
Blog Entries: 1

Rep: 564 rabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famousrabidgnome229 is becoming famous
Unique Rep: 338
FAQs Submitted: 6
Trader Rating: 5
Default

Quote:
Originally Posted by ghell View Post
Because it is faster. For a trivial program, it will not make a noticeable impact on performance anyway but for a large application or an application that involves a lot of number crunching on small data sets, the stack should be used. Using the heap unnecessarily will inevitably lead to memory leak anyway.

The simplest example of the heap being slower is that every time you read or write to the heap, you have to go through a pointer. Imagine the trivial case of storing a 32 bit integer on the stack vs storing a pointer to it on the heap. In order to read the integer from the stack, you can just read it directly into a register. In order to read it form the heap you must get the pointer into a register, go and find it on the heap and then get the value. When writing back you must do the same thing. This is just a small example that should hopefully be simple enough to see instantly without having to think about it but there are further causes of lower performance on the heap. You should be able to find plenty of information on these further details if you google phrases such as "stack faster than heap" or "stack vs heap".

The heap should mainly just be used where large amounts of data need to be used, such as when loading images. This is because the stack is a very small store in comparison.

The stack is also simpler so why overcomplicate things?
It seems that the difference is in allocation/deallocation. That makes sense - I was only thinking in terms of access.
__________________
BIG BROTHER
I put on my robe and wizard hat...

IS WATCHING

System: It goes to eleven
CPU
E6300
Motherboard
DS3
Memory
2GB XMS2 DDR2-800
Graphics Card
EVGA 8600GTS
Hard Drive
1.294 TB
Sound Card
Audigy 2 ZS
Power Supply
Corsair 520HX
Case
Lian-Li v1000B Plus
CPU cooling
TTBT
GPU cooling
Thermalright V2
OS
Arch Linux/XP
Monitor
Samsung 226bw
rabidgnome229 is offline Overclocked Account   Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -4. The time now is 07:45 AM.


Overclock.net is a Carbon Neutral Site Creative Commons License Internet Security By ControlScan

Terms of Service / Forum Rules | Privacy Policy | Advertising | Become an Official Vendor
Copyright © 2008 Shogun Interactive Development. Most rights reserved.
Page generated in 0.34819 seconds with 8 queries