返回C++中向量元素的复制值
Returning copied value of vector element in C++
我已经在SO和谷歌上搜索了3个小时,但找不到我所看到的分辨率。
我有一个.cpp矢量支持程序,它为更大的c程序提供c++功能。我已经有了一个工作良好的queue.cpp,队列推送和弹出来回传递的值/元素的副本,因此函数的导出和构建正在进行。
当试图复制并返回向量中元素的值时,会出现问题。
在.c文件中的使用
vector_type *temp;
...
_Vector_At(VectorHandle, i, temp);
if(temp == NULL)
printf("nulln");
printf("Returned %xn", temp);
.cpp:
typedef struct
{
std::vector<vectory_type*> q;
pthread_mutex_t mutex;
} VECTOR;
...
int _Vector_At(VECTOR_HANDLE handle, short index, vectory_type *ptr)
{
VECTOR *q = (VECTOR *)handle;
if (NULL == q)
{
return(-1);
}
ptr = q->q[index];
printf("Test %xn", ptr);
return(0);
}
控制台输出为
Test <expected memory address>
null
Returned 0
我只能在访问器函数内部查询ptr指向的值。当ptr的值从.cpp程序返回到.c程序时,它会被擦除。但是,std::queue以完全相同的方式推送和弹出值,这并没有任何意义。
有人有什么想法吗?谢谢
在c代码中,将vector_type *temp
传递给函数_Vector_At
。_Vector_At
函数正在将指针的本地副本作为ptr
,并使用它来修改值,但它并没有按照您的意愿返回该值。这是因为它是一个局部变量,它的生存期在_Vector_At
函数结束时结束。要解决此问题,可以将指针作为引用或指针指针传递:_Vector_At(VECTOR_HANDLE handle, short index, vectory_type* &ptr)
或_Vector_At(VECTOR_HANDLE handle, short index, vectory_type** ptr)
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 为什么复制而不是移动数据元素?
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- 调整大小和复制哈希表数组中的元素
- 如何在 2d 矢量 c++ 中复制元素并将其放在原始元素旁边
- C++将所有元素从矢量复制到地图/unordered_map的最佳方法
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- list.push_back似乎复制了最后添加的元素
- 如何使用指针C++将元素从2D数组复制到1D数组
- 将 Vector<String > 元素复制到其他 Vector<String>* (1 作为
- 如何将 n 个连续元素插入到元素类型不可复制的 std::vector 中?
- 如何将结构深度复制到向量的每个元素
- r-在Rcpp和C++之间转换矢量(使用Rcpp::as或Rcpp:::wrap)是否会创建一个新的矢量并复制元素
- C 是否每次访问数组时都复制元素?
- 在变量之间移动队列而不复制元素
- 矢量中的不可复制元素
- 无序映射插入复制元素
- Mat::p ush_back(x) 是否复制 x 元素
- 基于条件从vector复制元素