2014-10-28 36 views
1

我正在嘗試編寫一個存儲char名稱數組的程序。C++ char *錯誤,程序崩潰

這是我的代碼

#include <iostream> 
#include <string.h> 
using namespace std; 

char **names; 
char *input_name; 

int main() { 
    names = new char*[10]; 
    for(int i=0; i<10; i++){ 
     names = new char[60]; 
     cout << "Input name" << i << ": \n"; 
     cin >> input_name; 
     strcpy(names[i],input_name); 
     cout << names[i] << "\n"; 
    } 
    return 0; 
} 

首先我收到cannot convert ‘char*’ to ‘char**’ in assignment names = new char[60];錯誤。

而且,得到invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] strcpy(names[i],input_name);錯誤

我將不勝感激,如果有人可以修改我的代碼,並幫助我

感謝

+2

不應該'names = new char [60];'be'names [i] = new char [60];'?其他錯誤是前一個錯誤的副作用。 – alvits 2014-10-28 22:08:00

+1

如果名稱超過59個字符,祝你好運。 – PaulMcKenzie 2014-10-28 22:11:10

+0

@alvits謝謝:),但我仍然在輸入方面出現錯誤。我的代碼在IDEOne上 - http://ideone.com/PAMwgw – user4167396 2014-10-28 22:11:32

回答

2

這是names[i] = new char[60];,而不是names = new char[60]; 你忘了初始化input_name用input_name = new char[60];

#include <iostream> 
#include <string.h> 
using namespace std; 

char **names; 
char *input_name; 

int main() { 
    names = new char*[10]; 
    input_name = new char[60]; 
    for(int i=0; i<10; i++){ 
     names[i] = new char[60]; 
     cout << "Input name" << i << ": \n"; 
     cin >> input_name; 
     strcpy(names[i],input_name); 
     cout << names[i] << "\n"; 
    } 
    return 0; 
} 

當你使用C++時,你應該考慮使用std :: string而不是char *。正如PaulMcKenzie在評論中提到的,當一個名字超過59個字符時,你會遇到麻煩。加上std :: string更方便IMO。

+0

爲什麼我的程序崩潰,如果我不做'input_name = new char [60];'?我的程序在'cin >> input_name; strcpy(names [i],input_name)' – user4167396 2014-10-28 22:19:34

+0

你剛纔聲明瞭input_name應該是什麼,但從來沒有給它賦值。由於它是一個指針,它指向一個無效的內存地址。 – H4kor 2014-10-28 22:20:59

+0

@ user4167396因爲'input_name'指向哪裏? – 2014-10-28 22:21:18

0

該代碼包含大量內存泄漏!任何數據實際上應該是delete d。請注意,delete的形式需要與new的形式匹配,即,當分配了數組對象時,需要使用例如delete[] names來釋放數組對象。

if (std::cin >> std::setw(60) >> names[i]) { 
    // OK - do something with the data 
} 
else { 
    // failed to read characters: do some error handling 
} 

當你讀入一個char數組,你需要確保數據量的陣列中,在不超過,你可以限制的字符數通過設置流的寬度,例如讀取

當然,在您發佈的代碼片段中,您嘗試讀取input_name哪個指向無處:這將導致未定義(可能會導致一些崩潰)。