Question

This is my scenario.

struct X {
char A[10];
int foo;
};
struct X *x;
char B[10]; // some content in it.
x = malloc(sizeof(struct X));

To copy contents from B to A, why is the following syntax correct:

memcpy(x->A, B, sizeof(x->A));

Here x->A is treated as a pointer, so we don't need &. But then we should need sizeof(*x->A) right? But with * it is not working, while without * it's working fine.

Is it like sizeof operator does not treat A like a pointer?

Was it helpful?

Solution

A is NOT a pointer, it's an array. So sizeof(x->A) is the correct syntax, it's the size of the whole array, i.e, 10.

It's true that in many situations, an array name is converted to a pointer to the first element. But sizeof(arrayname) is NOT one of them.

OTHER TIPS

sizeof(*x->A) gives you the size of a char(1 byte), while size0f(x->A) gives you the size of the entire array(10bytes).

sizeof(*x->A) is equivalent to sizeof(x->A[0]).

sizeof(*x->A) is 1 bye here. So memcpy will happen for only one byte.

This is sizeof(x->A) is the correct procedure.

Though in many cases array name decay to a pointer (like the first argument to memcpy() in your example), there are a few that don't and sizeof operator argument is one of them. Other examples are unary & operator argument, etc. C++ has more scenarios (e.g. initializer for array reference).

Just to add on to previous comments

sizeof(x->A) is correct sizeof(*x->A) is not correct because -> has higher precedence than * so first the address of A is obtained(X->A) then * again deference's it to first byte (one char byte).

Not to forget sizeof operator doesn't consider '\0' character. if the the string "Hello" is pointed by A then it returns 5 ( array size is 6 including '\0'), so while copying to B you have to add '\0' explicitly or you can increase the number bytes to be copied by one as shown below.

memcpy(x->A, B, sizeof(x->A) + 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top