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);
}
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, ie 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. You were also not using malloc
correctly. 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 * sizeof(char**)); // 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.