C++ functions returning arrays

后端 未结 3 1882
梦谈多话
梦谈多话 2021-01-14 23:55

I am sort of new to C++. I am used to programming in Java. This particular problem is causing me great issues, because C++ is not acting like Java when it is dealing with Ar

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-15 00:35

    The problem is that you cannot return local arrays:

    int a[] = {1, 2, 3};
    ...
    return a;
    

    is invalid. You need to copy a into dynamic memory before returning it. Currently, since a is allocated in the automatic storage, the memory for your array gets reclaimed as soon as the function returns, rendering the returned value invalid. Java does not have the same issue because all objects, including arrays, are allocated in the dynamic storage.

    Better yet, you should avoid using arrays in favor of C++ classes that are designed to replace them. In this case, using a std::vector would be a better choice.

提交回复
热议问题