2016-09-14 95 views
-4

我正在写一个类的c + +应该添加一个字符串指针到一个数组。而不是添加一个指向字符串的指针我只是将第一个字符添加到数组中,但我希望能够在之后调用整个字符串。如何将字符串的指针添加到列表中,以便我可以打印出整个字符串?使C++中的字符串指针和数组的指针

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); 

} 
+1

选择C++。 'std :: vector'是你的朋友反对UB&内存泄漏。 –

+1

'class Listptr {''Listptr :: Listptr(){'这显然是C++代码;请不要将C++代码标记为C. –

+0

是不是有没有使用'std :: string'的原因? –

回答

1

你真的应该使用std::stringstd::vector<std::string>什么的,因为我在评论中提到。但是,您的代码有几个问题,我在下面解决了这个问题。主要是你需要一个指向char数组的指针,即一个char**而不是一个char*,然后你需要检查以确保你没有试图打印一个只是一个空指针的char数组。你也没有正确使用malloc。因此,对于教育目的,了解你做错了什么,而不是只说“停下来,”这里的固定码:

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); 
} 

输出

test test test2 
+0

我也同意关于'new'over'malloc'等问题的意见,但这是我认为最接近你的代码的工作版本。 –

+2

如果你喜欢内存泄漏,它“起作用”。 – PaulMcKenzie

+0

好点;我添加了一个析构函数。 –