&a v.s. a v.s. &a[0]

W

Wenjie

Hello,


I have an array: unsigned char a[1024];
I want to copy some data into it:
memcpy(a, anotherArray, sizeof(a));

But I saw somebody is using this:
memcpy(&a, anotherArray, sizeof(a));
And it passed the tests (VC++6.0).

Could someone confirm me that the 2nd use of
of &a is not valid? Why?
Also I would think it is OK to do:
memcpy(&a[0], anotherArray, sizeof(a));


Best regards,
Wenjie
 
J

John Harrison

Victor Bazarov said:
Wenjie said:
I have an array: unsigned char a[1024];
I want to copy some data into it:
memcpy(a, anotherArray, sizeof(a));

But I saw somebody is using this:
memcpy(&a, anotherArray, sizeof(a));
And it passed the tests (VC++6.0).

Could someone confirm me that the 2nd use of
of &a is not valid? Why?

I don't think someone would be able to confirm that because
it's valid. Expressions 'a' and '&a' have different _type_
but the same _value_. Used with memcpy, they are converted
to 'void*' of the same value, which then is passed to memcpy
and gives the same result.

You would pretty quickly see the difference though if you did this

memcpy(&a + 1, anotherArray, sizeof a - 1);

or this

memcpy(a + 1, anotherArray, sizeof a - 1);

or this

memcpy(&a[1], anotherArray, sizeof a - 1);

The first is a bug, the second and third are OK. Try printing out the
pointer values to see the difference.

john
 
V

Victor Bazarov

John Harrison said:
Victor Bazarov said:
Wenjie said:
I have an array: unsigned char a[1024];
I want to copy some data into it:
memcpy(a, anotherArray, sizeof(a));

But I saw somebody is using this:
memcpy(&a, anotherArray, sizeof(a));
And it passed the tests (VC++6.0).

Could someone confirm me that the 2nd use of
of &a is not valid? Why?

I don't think someone would be able to confirm that because
it's valid. Expressions 'a' and '&a' have different _type_
but the same _value_. Used with memcpy, they are converted
to 'void*' of the same value, which then is passed to memcpy
and gives the same result.

You would pretty quickly see the difference though if you did this

memcpy(&a + 1, anotherArray, sizeof a - 1);

or this

memcpy(a + 1, anotherArray, sizeof a - 1);

or this

memcpy(&a[1], anotherArray, sizeof a - 1);

The first is a bug, the second and third are OK. Try printing out the
pointer values to see the difference.

The point is that they will still compile. The "bug" is due
to undefined behaviour, not due to "illegal C++ construct".

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top