這個問題在這里已經有了答案: 可以在其作用域之外訪問區域變數的記憶體嗎? (21 個回答) 14 小時前關閉。
考慮:[1]
int *func(){
int a[10];
//...
return a;
}
int main(){
int* a = func();
}
//在函式里開陣列后往main函式回傳指標
[2]
void func(int a*){
//...
}
int main(){
int a[10];
func(a);
}
//在main函式開個陣列后傳實參到函式里
兩個程式可以定義一個陣列a并使用它。哪一個更好?為什么?在記憶體分配和性能上有啥區別?更推薦清潔方式?
uj5u.com熱心網友回復:
兩個代碼可以定義一個陣列a并使用它,哪個更好?為什么?
第二個更好,因為第一個很簡單。您回傳一個指向陣列的指標,該陣列在函式回傳后將不再存在。換句話說,一個懸空指標。
uj5u.com熱心網友回復:
我在 C 中所做的也不是我會使用這些結構之一:
#include <array>
void function(int values[10])
{
}
template<std::size_t N>
void function_template(int(&values)[N])
{
}
template<std::size_t N>
void function_const_ref(const std::array<int, N>& arr) // pass by const reference if you only want to use values
{
}
template<std::size_t N>
void function_ref(std::array<int, N>& arr)
{
arr[1] = 42;
}
int main()
{
int arr[10]{}; // {} also initializes all values to 0!
function(arr);
function_template(arr); // keeps working even if you change size from 10 to something else
// or use std::array and you ca
std::array<int, 10> arr2{};
function_ref(arr2);
// this is I think the most C way
function_const_ref(arr2);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368923.html
下一篇:無法理解位移如下
