Anwar Mohamed
Anwar Mohamed

Reputation: 653

how to memcpy() a constant

How can I memcpy() a constant in c++ for example I have defined a constant using

#define constant1 0x0080

when i want to

memcpy(&some_memory_block, constatnt1, 2 );

it says

error C2664: 'memcpy' : cannot convert parameter 2 from 'int' to 'const void *'

Upvotes: 1

Views: 12755

Answers (3)

Damon
Damon

Reputation: 70186

Your constant (macro) is really just a literal. As such, it has no address which could be given as parameter to memcpy or another function that expects a memory location. If you want to do this, you need to have a real constant (such as const int), as suggested in the other answers.
A real constant as opposed to a macro (which is just a text substitution, in this case for a literal) is normally functionally identical to a literal, as long as you don't take its address. However, it is possible to take its address, at which point it behaves like a "normal" variable. Which means that you can use memcpy on its address.

The usually "more correct" answer, however, is: Don't do this kind of thing at all. If something is a constant, you shouldn't copy it around (there exist exceptions of course, but usually you just shouldn't). The only valid reason would be that you want a constant value to initialize a non-constant variable, but then it's much easier to just assign it than to memcpy.

Making copies of a constant otherwise only adds redundancy, eats up extra memory at no benefit, increases cache pressure, and defeats many compiler optimizations. For example, a compiler can trivially optimize an expression like a = b + c - c + b to a = computed_value_of_2b if it knows that the symbols are constants (much more complicated and less obvious expressions are evaluated too, of course). However, the compiler has to emit code that evaluates at runtime when given some memory locations, it has no other choice.

Upvotes: 3

user1944441
user1944441

Reputation:

What happen in your case is that constant1 gets replaced by 0x0080 when you compile the code. And this line

memcpy(&some_memory_block, constatnt1, 2 );

becomes

memcpy(&some_memory_block, 0x0080, 2 );

this


If you look at memcpy you will see that memcpy requiers a pointer for the second parameter.

You have to assing a pointer to the memcpy

const int constant1 = 0x0000;
memcpy(&some_memory_block, &constant1 , 2 );

Upvotes: -1

scones
scones

Reputation: 3345

You could try using a constant, instead of a precomiler definition.

const unsigned short int constant1 = 0x0080;
memcpy(&some_memory_block, &constant1, 2 );

Upvotes: 4

Related Questions