-2

Consider: [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函数开个数组后传实参到函数里

Two programs can define an array a and use it. Which one is better? Why?在内存分配和性能上有啥区别?更推荐哪种方式?

Eter
  • 1
  • 1

2 Answers2

1

Two codes can define an array a and use it.Which one is better? Why?

The second is better because the first is plain broken. You return a pointer to an array that will no longer exist once the function returns. In other words a dangling pointer.

Homer512
  • 9,144
  • 2
  • 8
  • 25
0

Neither is what I would do in C++ I would use one of those constructs:

#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;
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19