calloc and copying data into memory area using c -
I am trying to allocate blocks of memory and then copying the data in that location. I made this simple program and it does not do what I hope is to do it. Someone can tell my faulty reasoning.
Thank you.
#include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; Zero main (zero) {int t1 = 11; Int T2 = 22; Int * bufptr; Bufptr = calloc (2, size); If (bufptr == NULL) {fprintf (stderr, "Out of memory, exit \ n"); Exit (1); } Memcpy (bufptr, & amp; t1, sizeof (int)); Memcpy ((bufptr + sizeof (int)), & amp; t2, sizeof (int)); Printf ("bufptr11:% d \ n", * bufptr); Printf ("bufptr22:% d \ n", * bufptr + sizeof (int)); }
It prints it as follows:
bufptr11: 11
bufptr22: 15 (this should not be 22 more 15)
Thanks All help all, but I just ran into my next stop! The whole point of this exercise is to send some data to another host via UD. Before I sendto (), before I look at the contents of bufptr, everything looks fine and it is good to send. On the other hand (I'm running client / server 127.0.0.1) I'll just get "fuck" I call recvfrom (s_fd, bufptr, buflen, etc.). I use the same callk call to allocate memory for bufptr, this is the right amount of data from this call, but its content is just nonsense!
bufptr = calloc (2, size (int)); If (bufptr == NULL) {fprintf (stderr, "Out of memory, exit \ n"); Exit (1); } Buflen = 2 * sizeof (int); RC = Recupfrom (SD, Bufter, Bufflin, 0, (Structured Socadar *) and Server Adrer, and Server Adlon); Printf ("t2:% d \ n", * bufptr); Printf ("t3:% d \ n", * (bufptr + 1));
Try these:
memcpy (bufptr , & Amp; t1, size (int)); // Copy 11 in the first element of the array. Mempi (bufptr + 1, and T2, sizaf (int)); // bufptr + 1 will point to the next int on the array. Printf ("bufptr11:% d \ n", * bufptr); Printf ("bufptr22:% d \ n", * (bufptr + 1)); // is required in the form of bracket * +
Comments
Post a Comment