C++中的数组创建
Array Creation in C++
我本质上想做的是编写一个函数,它可以使用长度为n的数组,并生成长度为n-2的数组。这是我到目前为止的代码:
float* comp_arr(float vals[], int arr_size, float scale, float dim){
int arr_dim = (int)(arr_size+1-2*scale);
float curvs[arr_dim];
for(int i = scale; i < sizeof(vals)-scale+1; i++){
float cur = comp_cur((i-scale)*dim, vals[i-1], i*dim, vals[i], (i+scale)*dim, vals[i+1]);
int new_index = (int)(i-scale);
curvs[new_index] = cur;
printf("%fn",cur);
}
return curvs;
}
我在主要函数中这样调用它:
main(){
float vals [] = {2,3,6,1,7};
float *curvs = comp_arr(vals,5,1.0,1.0);
}
但是我得到了这个错误:
comp.cpp: In function ‘float* comp_arr(float*, int, float, float)’:
comp.cpp:35:8: warning: address of local variable ‘curvs’ returned [enabled by default]
/tmp/ccrDJjYq.o: In function `comp_arr(float*, int, float, float)':
comp.cpp:(.text+0x590): undefined reference to `__cxa_end_cleanup'
/tmp/ccrDJjYq.o:(.ARM.extab+0xc): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
我对C++还很陌生,我做错了什么?????
curvs
数组是comp_arr函数中的局部变量。抛出第一个警告是因为一旦此函数返回,它所使用的内存(包括curvs
数组)将超出范围。在main中引用返回的数组将导致未定义的行为;如果您想从函数返回一个数组,则必须通过new/malloc动态分配它。
您正在返回一个指向局部变量的指针。一旦到达comp_arr
函数的右大括号,curvs
就不在作用域内,不再存在,但您正在返回它的地址。如果数据仍然存在于内存中,程序甚至可以正常运行,但它可能随时被覆盖。
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?