我是新手,學習 C ,嘗試動態分配一個字串陣列并由用戶輸入每個字串。所以首先,用戶輸入字串的數量,然后使用cin>>
int main() {
int numberOfTeams;
char** Teams;
cout << "Enter the number of teams " << endl;
cin >> numberOfTeams;
Teams = new char* [numberOfTeams] ;
for (int i = 0; i < numberOfTeams; i ) {
cin >> Teams[i];
}
delete[] Teams;
return 0;
}
該程式在cin一個字串后把我扔出去。我得到的錯誤是:
Exception thrown: write access violation.
**_Str** was 0xCEDECEDF.
我不能使用“字串”,只能使用字符陣列。
謝謝你們
uj5u.com熱心網友回復:
像這樣的東西
const int MAX_STRING_SIZE = 1024;
int main() {
int numberOfTeams;
char** Teams;
std::cout << "Enter the number of teams " << std::endl;
std::cin >> numberOfTeams;
Teams = new char*[numberOfTeams];
for (int i = 0; i < numberOfTeams; i ) {
Teams[i] = new char[MAX_STRING_SIZE];
std::cin >> Teams[i];
}
for(int i = 0; i < numberOfTeams; i) {
delete [] Teams[i];
}
delete [] Teams;
return 0;
}
uj5u.com熱心網友回復:
char** 是指向字符指標陣列的指標。您要做的第一件事是分配字符指標陣列,
Teams = new char*[numberOfTeams];現在 Teams 指向 numberOfTeams char* 指標中的第一個 char*。您的錯誤是對于陣列中的每個 char* 指標,您沒有執行分配。這是正確的解決方案。
#include <iostream>
using namespace std;
int main() {
int numberOfTeams;
int teamNameLength = 32;
char **Teams;
cout << "Enter the number of teams " << endl;
cin >> numberOfTeams;
Teams = new char*[numberOfTeams];
for (int i = 0; i < numberOfTeams; i )
{
Teams[i] = new char[teamNameLength];
}
for (int i = 0; i < numberOfTeams; i ) {
cout << "Enter team name " << i 1 << endl;
cin >> Teams[i];
}
for (int i = 0; i < numberOfTeams; i ) {
delete[] Teams[i];
}
delete[] Teams;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381634.html
上一篇:使用in連接陳述句的速度相加
