Page 1 of 1

pointers to pointers, very scalable. take a looksee.

Posted: Sun Mar 08, 2009 4:02 pm
by avansc

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_ATTRIBUTE 3
enum attribute { name, lastname, number };

class snip
{
public:
    snip();
    void setAttribute(attribute attr, char *data);
    char *getAttribute(attribute attr);
private:
    char **data;
};

snip::snip()
{
    this->data = (char**)malloc(sizeof(char*));
}

void snip::setAttribute(attribute attr, char *data)
{
    this->data[attr] = (char*)malloc(sizeof(char)*strlen(data));
    strcpy(this->data[attr], data);
}

char *snip::getAttribute(attribute attr)
{
    return this->data[attr];
}


int main (int argc, char * const argv[])
{
    snip *temp = new snip();
    
    temp->setAttribute(name, "andre");
    temp->setAttribute(lastname, "van");
    temp->setAttribute(number, "1234");
    
    for(int a = 0;a < NUM_ATTRIBUTE;a++)
    {
        printf(":= %s\n", temp->getAttribute((attribute)a));
    }
    
    return 0;
}

if you have any questions on this please feel free to ask.

Re: pointers to pointers, very scalable. take a looksee.

Posted: Mon Mar 09, 2009 1:20 am
by Spikey
That's pretty cool!
I have 1 question though, I notice you never free() memory in this example. So to prevent leaks, would you have to free() each attribute individually or would just freeing **data in the destructor suffice?
In any case, thanks for sharing.

Re: pointers to pointers, very scalable. take a looksee.

Posted: Mon Mar 09, 2009 12:32 pm
by avansc
Spikey wrote:That's pretty cool!
I have 1 question though, I notice you never free() memory in this example. So to prevent leaks, would you have to free() each attribute individually or would just freeing **data in the destructor suffice?
In any case, thanks for sharing.
yeah you would have to free some stuff. im not sure exactly now. so i dont wanna tell you the wrong thing. let me do some research and get back to you.

Re: pointers to pointers, very scalable. take a looksee.

Posted: Mon Mar 09, 2009 2:42 pm
by wtetzner
Spikey wrote:So to prevent leaks, would you have to free() each attribute individually or would just freeing **data in the destructor suffice?.
You would have to free each item in data, then free data.