該程式的輸入如下:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
我想n成為一個指向其他整數陣列的陣列。所以,n本質上應該是{{1, 5, 4}, {1, 2, 8, 9, 3}}。如果我想訪問第 0 個陣列和第 1 個索引,值應該回傳5,如果我要訪問第 1 個陣列和第 3 個索引,值應該是9。
但是,此代碼回傳的值是32764和32764。
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int n_l; // integer variable that will hold the length of array n
int q_l; // integer variable that will hold the length of the number of queries
cin >> n_l >> q_l; // assigns values to the variables n_l and q_l
int *n[n_l]; // creates an array that will contain pointers
for (int i = 0; i < n_l; i ){ // loops through the length of array n
int amount; // declares the variable amount
cin >> amount; // assigns a value to the variable amount
int k[amount]; // creates one of the arrays that will be added to n
for (int x= 0; x < amount; x ){ // loops through the length of k and assigns a value to each index
cin >> k[x];
}
n[i] = k; // adds the array k to the position in array n
}
for (int i = 0; i < q_l; i ){
int arraynum;
int index;
cin >> arraynum >> index;
cout << n[arraynum][index] << endl;
}
}
uj5u.com熱心網友回復:
您在 for 回圈中定義陣列,其范圍將在該回圈中受到限制,嘗試使用newfor 陣列分配區域并將新分配區域的地址保存到指標陣列中。
for (int i = 0; i < n_l; i ){ // loops through the length of array n
int amount; // declares the variable amount
cin >> amount; // assigns a value to the variable amount
int *k = new int[amount];
for (int x= 0; x < amount; x ){ // loops through the length of k and assigns a value to each index
cin >> k[x];
}
n[i] = k; // adds the array k to the position in array n
}
完成后,不要忘記洗掉分配的區域:
for(int i = 0; i < n_l; i )
delete[] n[i];
uj5u.com熱心網友回復:
對于初學者來說,可變長度陣列不是標準的 C 特性
int *n[n_l];
相反,您可以使用std::vector<int *>. 或者您可以使用std::vector<std::pair<int, int *>>where 對的第一個元素存盤動態分配陣列中的元素數量,而對的第二個元素存盤指向動態分配陣列的指標。
此外,陣列將包含無效指標,因為在 for 回圈中宣告的陣列
int k[amount];
退出 for 回圈后將不再存在。
所以至少你必須在 for 回圈中動態分配陣列。
在訪問動態分配陣列的元素之前,您需要檢查輸入的索引是否對給定陣列有效。
uj5u.com熱心網友回復:
cin >> n_l >> q_l; // assigns values to the variables n_l and q_l int *n[n_l];
這在 C 中是不允許的。陣列變數的大小必須是編譯時常量。您可以創建動態陣列。最方便的方法是使用std::vector標準庫中的類模板。
您的指標的問題在于,您在回圈中創建的自動陣列在回圈陳述句結束時會自動銷毀,并且陣列中的指標都是指向已銷毀陣列的懸空(即無效)指標。當您稍后通過無效指標間接時,程式的行為是未定義的。
你想要多個陣列。創建多個物件的好方法是什么?陣列是創建多個物件的好方法。因此,為了創建多個陣列,您可以創建一個陣列陣列。或者,由于您想要動態大小,您可以創建一個向量向量。以下是如何創建向量向量的示例:
std::vector<std::vector<int>> n(n_l);
for(auto& vec : n) {
int amount;
std::cin >> amount;
vec.resize(amount);
for(auto& i : vec) {
cin >> i;
}
}
您可以在向量向量中創建指向向量內陣列的指標向量,但這毫無意義。你不需要指標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462778.html
下一篇:斷言指標與某個值對齊
