Chemistpp Chemistpp - 1 year ago 103
C++ Question

Equivalent memcpy different results?

I used memcpy to copy a struct

comprised of glm::vec3 objects.
It worked to copy the struct in a class function.
It did not work in the copy constructor that was called when that function returned the class object.


Class function returning object

ShapeData ShapeGenerator::drawTriangle() {
ShapeData ret;

Vertex verts[] = {
glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(1.0f, 0.0f, 0.0f),

glm::vec3(-1.0f, -1.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),

glm::vec3(1.0f, -1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f),

ret.numVerts = NUM_ARRAY_ELEMENTS(verts);
ret.verts = new Vertex[ret.numVerts];
memcpy(ret.verts, verts, sizeof(verts)); //WORKS

GLushort indicies[] = {0,1,2};
ret.numIndicies = NUM_ARRAY_ELEMENTS(indicies);

ret.indicies = new GLushort[ret.numIndicies];
memcpy(ret.indicies, indicies, sizeof(indicies));

return ret;

Copy Constructor

ShapeData(const ShapeData& data) {

verts = new Vertex[data.numVerts];
//memcpy(verts, data.verts, sizeof(data.verts)); //DOES NOT WORK
std::copy( data.verts, data.verts + data.numVerts, verts);

indicies = new GLushort[data.numIndicies];
memcpy(indicies, data.indicies, sizeof(data.indicies));

numVerts = data.numVerts;
numIndicies = data.numIndicies;

std::cout << numVerts << std::endl;



#ifndef VERTEX_H
#define VERTEX_H

#include <glm/glm.hpp>

struct Vertex {
glm::vec3 position;
glm::vec3 color;


Answer Source
memcpy(verts, data.verts, sizeof(data.verts)); //DOES NOT WORK

does not work since verts is a pointer, not an array. sizeof(data.verts) does not evaluate to the size of the array the pointer points to. It simply evaluates to the size of a pointer on your platform.

You should be able to use:

size_t n = sizeof(*data.verts)*data.numVerts;
memcpy(verts, data.verts, n);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download