你好我有一個疑問下面的代碼是如何作業的?
#include <iostream>
using namespace std;
int main()
{
int* arr = new int;
arr[0] = 94;
arr[1] = 4;
cout << arr[0] << endl;
}
為什么這會告訴我一個錯誤我應該怎么做
#include <iostream>
using namespace std;
struct test
{
int data;
};
int main()
{
test* arr = new test;
arr[0] -> data= 4;
arr[1] -> data= 42;
cout << arr[0]->data << endl;
}
uj5u.com熱心網友回復:
在您的代碼中:
#include <iostream>
using namespace std;
int main()
{
int* arr = new int;
arr[0] = 94; // This will work
arr[1] = 4; // This will cause undefined behaviour
cout << arr[0] << endl;
}
在上面的代碼中,arr是指向單個的指標int,因此您可以int使用以下任一方法訪問該代碼:
arr[0]
*arr
..但是 arr 1不起作用,因為沒有為陣列分配足夠的記憶體。
要解決此問題,您必須為 arr 分配更多記憶體:
int* arr = new int[2];
..并更改 arr 的大小:
int arr_size = 2;
int* arr = new int[arr_size]; // size of arr = 2
arr[0] = 12;
arr[1] = 13;
int* new_arr = new int[arr_size 1];
for (int i = 0; i < arr_size; i )
{
new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;
// size of arr = 3
arr但是當有大量元素時,所有這些都會在計算上變得昂貴且耗時。所以我建議使用C 's std::vector:
您的第二個程式使用std::vector:
#include <iostream>
#include <vector>
struct test
{
int data;
};
int main()
{
std::vector<test> vec{ test(4), test(42) };
std::cout << vec[0].data << std::endl;
}
有關更多資訊std::vector,請單擊此處。
另外,請考慮不要在代碼中使用以下行:
using namespace std;
..as it's considered as bad practice. For more info on this, look up to why is "using namespace std" considered as bad practice.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435806.html
