gpt4 book ai didi

c++ - 从函数返回指向二维数组的指针 - C++

转载 作者:行者123 更新时间:2023-11-30 05:12:44 37 4
gpt4 key购买 nike

所以我想要实现的是从函数返回一个指向二维数组的指针,以便它可以在 main() 中访问。我知道有一些 C++ 库可以像 std::vector 那样为你做这件事,但我试图避免动态内存分配,因为我在嵌入式板 (STM32) 上工作,所以我会坚持正常指针和数组。 (还有一些原因,我不能在 KEIL uVision 中使用 std::array,这也是我被迫使用指针/数组的原因)

此外,我知道返回一个指向函数内部定义的局部数组 int arr[2][2] 的指针不是一个好主意,因为它在函数之后将不再有效返回,这就是为什么我创建 test_array,在类中声明它并在函数中定义它(充当全局变量)所以我认为这应该不是问题。你们有什么感想?但是,这样做会产生错误 "Excess elements in scalar initializer"

#include <iostream>
#include "file.hpp"

int main() {

myClass class_object;

class_object.value = class_object.foo();


}

//file.hpp

#include <stdio.h>

class myClass{

int array[2][2];
int (*foo())[2];
int (*value)[2];

int test_array[2][2]; //declaring here!

};

//file.cpp 

#include "file.hpp"

int (*myClass::foo())[2]{

test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

int arr[2][2]= {
{1, 10},
{20, 30}
};


return arr;


}

最佳答案

眼前的问题:

test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

没有定义。 test_arraymyClass 中定义。这是试图分配给 test_array 的单个元素,特别是 [2][2] 不存在。尤其让编译器反感的不是越界访问,而是 ={ {10,20}, {30, 40} }; 试图将数组填充到单个数组元素中。编译器需要一个数字,所以四个数字肯定是多余的。

不幸的是,我不知道做您想做的事的好方法。您可以使用初始化列表初始化数组,但不能从一个列表进行赋值。

所以

class myClass{
public:

myClass();
void foo();

int test_array[2][2]; //declaring here!
};

// you can do this:
myClass::myClass(): test_array{ {10,20}, {30, 40} }
{

}

void myClass::foo()
{
// but you can't do this:
test_array = { {10,20}, {30, 40} };
}

根据您对 test_array 所做的操作,在构造函数中进行初始化可能适合您。如果您必须在每次调用 foo 时重置数组,也许 Automatic 变量更适合您

void myClass::foo()
{
int temp_array[2][2] = { {10,20}, {30, 40} };

// use temp_array

// maybe copy temp_array to test_array with good ol' memcpy here if you
// need to carry the state for some reason.
}

让房间里的大象安静下来and gain access to std::array, give this a try.注意:我从来没有这样做过。就我所知,这可能是一场彻头彻尾的灾难,所以请持保留态度。

关于c++ - 从函数返回指向二维数组的指针 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44378973/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com