Memcpy en una matriz dentro de una estructura mallada

Este es mi escenario.

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 a A, why is the following syntax correct:

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

Aquí 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 * está funcionando bien.

Es como sizeof operator does not treat A like a pointer?

preguntado el 12 de febrero de 14 a las 05:02

5 Respuestas

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) NO es uno de ellos.

Respondido 12 Feb 14, 05:02

is this behavior of sizeof consistent on different C implementations and platforms. I now know it works this way with gcc on a x86 linux machine. What about others? - vivekzhere

@vivekzhere It's guaranteed by the C standard, so all implementations should follow this rule. - yuhao

@vivekzhere But be careful when the array name is passed as function argument, it decays into a pointer in that case. - yuhao

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).

Respondido 12 Feb 14, 05:02

sizeof(*x->A) es equivalente a sizeof(x->A[0]).

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

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

Respondido 12 Feb 14, 05:02

El tamaño de x->A[0] is the size of one char, which is (by definition) 1. - jonathan leffler

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).

Respondido 12 Feb 14, 05:02

Just to add on to previous comments

sizeof(x->A) es correcta sizeof(*x->A) no es correcto porque -> tiene mayor precedencia que * 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 tienes que agregar '\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);

Respondido 12 Feb 14, 05:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.