Memcpy en una matriz dentro de una estructura mallada
Frecuentes
Visto 409 equipos
2
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?
5 Respuestas
2
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
2
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
1
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
0
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
0
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
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