0
Could anyone tell me why this problem occurs below? It does not copy the last position of the pointer vector, with the value 57, to another pointer vector. This intrigues me, why not copy this last position?
int main()
{
int i;
int *v;
int *k;
k = malloc(100*sizeof(int));
memset(k,0,sizeof(k));
k[0]=78;
k[1]=63;
k[2]=57;
v = malloc (10 * sizeof (int));
memset(v,0,sizeof(v));
printf("Valor que não quer imprimir no vetor:%d\n",k[2]);
//*(v+i) = 789;
//v[i] = 789;
for (i = 0; i < 2; ++i)
{
printf("\nDigite um valor:");
scanf ("%d", &v[i]);
}
for (i = 0; i < 2; ++i) printf("%d\n",v[i]);
printf("\nResultado:");
memcpy(&v[2],k,sizeof(k));
for (i = 0; i < 5; ++i) printf("\n%d",v[i]);
return 0;
}
As a result, this output:
Valor que não quer imprimir no vetor:57
Digite um valor:1
Digite um valor:2
1
2
Resultado:
1
2
78
63
758396511
Process returned 0 (0x0) execution time : 12.095 s
Press any key to continue.
In memset, is not zeroing all items... Can someone give me a hand? Thank you very much!
The same goes for the
memcpy
.– sbrubes
the program is confused, not sure about memcpy
– zentrunix
Thank you for answering. In this case this part: memcpy(&v[2],k,sizeof(k)); Ali I say to copy all the contents from k to v, from position 2 of v. However not all values of k are copied. His last position is not copied, I do not understand why.
– Bianca Nunes
@Bianca Nunes: this explanation of yours makes no sense, because the size of v is 10sizeof(int) and the k is 100sizeof(int), so what you want to do is "memcpy(&v[2], k, 98*sizeof(int));", so you want to copy 98 ints to an address where there are only 8 ints available! will not give syntax error, but will overwrite memory you did not allocate; will "v" should not be declared with size 100 as well ?
– zentrunix
@Bianca Nunes, you are making confusion in "sizeof": when you do "sizeof(k)" you are picking the variable size k, which is a pointer, so this size will be 4 or 8 (depending on the compilation be 32 bits or 64 bits(
– zentrunix
I was testing with higher values there, and I forgot to leave it as it was. Actually, before it was 10. Even so, the error remains, does not copy the last position.
– Bianca Nunes
@Bianca Nunes then insert an updated version of your code, otherwise it will be impossible to know what is wrong
– zentrunix
Now I understood your explanation more up there. I replaced sizeof(k) with sizeof(int)*10 and it worked. Thank you.
– Bianca Nunes
@Biancanunes please then mark the answer as accepted
– zentrunix
Sorry, where’s that option?
– Bianca Nunes
on the left, below that arrow pointing down, there is a little "ok" sign that you click to mark an answer as it accepts...see here an explanation and an image: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-accepta reply
– zentrunix