moonboon moonboon - 2 months ago 7
C++ Question

make and array of pointers to strings in c++

I am writing a class in c++ that should add pointers of a string to an array. Instead of adding a pointer to a string I'm only adding the first character to the array but I want to be able to recall the whole string afterwards. How can I add a pointer of the string to the list so that I can print out the whole string?

class Listptr{
public:
Listptr();
void append(char *item);
private:
int size = 5;
char * buffer;
};

Listptr::Listptr(){
buffer = (char*)malloc(size);
for(int i=0; i<size; i++){
buffer[i] = NULL;
}
}

void Listptr::append(char *item){
for(int i=0; i<size; i++){
if(buffer[i] == NULL){
buffer[i] = *item;
break;
}
}

for(int i=0; i<size; i++){
cout << " " << buffer[i];
}
}


int main() {
Listptr test;
char val[] = "test";
char val2[] = "test2";
test.append(val);
test.append(val2);

}

Answer

You should really use std::string and std::vector<std::string> or something, as I mentioned in the comments. However, there were several problems with your code, which I've fixed below. Mainly you want a pointer to char arrays, i.e. a char**, not a char*, and then you need to check to make sure you're not trying to print a char array that's just a null pointer. So for educational purposes, to understand what you did wrong and not just say "stop it," here's the fixed code:

class Listptr{
    public:
        Listptr();
        void append(char *item);
    private:
        int size = 5;
        char ** buffer; // char**
};

Listptr::Listptr(){
    buffer = (char**)malloc(size); // char**
    for(int i=0; i<size; i++){
        buffer[i] = NULL;
    }
}

Listptr::~Listptr() {
    // Add destructor to free malloc-allocated memory when we're done
    free(buffer);
}

void Listptr::append(char *item){
    for(int i=0; i<size; i++){
        if(buffer[i] == NULL){
            buffer[i] = item;
            break;
        }
    }

    for(int i=0; i<size; i++){
        if (buffer[i] != NULL) { // Do not dereference null pointer
            cout << " " << buffer[i];
        }
    }
}


int main() {
    Listptr test;
    char val[] = "test";
    char val2[] = "test2";
    test.append(val);
    test.append(val2);
}

Output

 test test test2
Comments