c++ - 将指针指向的数据复制到另一个指针

标签 c++ pointers copy

我看过一些类似的问题,但没有解决方案适用于我的情况。

我有一个类具有持续运行的更新功能。此函数有一个 unsigned short* 参数,其中包含图像的二维数据,每次调用 update 时都不同。在执行开始时,我想将第一帧数据保存在单独的 unsigned short* 中,并且此数据必须在所有执行过程中都有效。

//setup在开始执行时运行一次

void Process::setup() 
{
    ...
    _firstFrame = new unsigned short; //_firstFrame is an unsigned short* private variable from the class

    return;
}

void Process::update(unsigned short* frame)
{   
    //-- Performing an initial calculation before any further processing
    if (!_condition)
    {
        //some processing that changes condition to true when criteria is met
        if (condition)
            memcpy(_firstFrame, frame, sizeof(640*480*sizeof(unsigned short)));
                    //each frame has 640*480 dimensions and each element is an unsigned short

        return;
    }

    //further processing using frame
}

现在,_firstFrame 应该始终保留来自满足条件后产生的帧的数据,但 _firstFrame 仅包含零。 有帮助吗?

最佳答案

您需要一个数组,但您总是需要它,因此没有必要动态分配它。

你还需要初始化它,恰好一次,所以你需要一些方法来跟踪它。当前,您(尝试)在不知道应该放入什么时分配您的第一帧。

class Process {
  bool got_first;
  unsigned short first_frame[640*480];

public:
  Process() : got_first(false) {}

  void update(unsigned short *frame) {
    if (!got_first) {
      memcpy(first_frame, frame, sizeof(first_frame));
      got_first = true;
    }
  }
};

关于c++ - 将指针指向的数据复制到另一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883373/

相关文章:

c - 无法理解这个常量指针错误

javascript - 我的 JavaScript 复制到剪贴板代码不起作用

c++ - 获取平面的角点

python - 将 std::string 传递给 PyObject_CallFunction

c++ - C++中使用成员函数删除对象

c - C 中矩阵的段错误

linux - 如何以定义的延迟复制文件集

database - 复制数据库 SQL Server 2012 中的 "The job failed"

c++ - 使用条件语句迭代 multimap

c++ - 在 C++ 中调用临时对象的析构函数的顺序是什么?