-2

The following is an example showing what I want:

int buf[3] = {10, 20, 30};
int * send_buf = (int *)malloc(5 * sizeof(int));

*send_buf = 1;
*(send_buf + 4) = 1;

After copy buf to send_buf, the values in send_buf should be :

1 10 20 30 1 

Could anyone let me know what's the most efficient way to do this without using memcpy() or memmove()?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 9
    why don't you want to use `memcpy`? – Lee Taylor Jul 25 '14 at 15:53
  • 2
    `send_buf[1] = buf[0]; send_buf[2] = buf[1]; send_buf[3] = buf[2];` Also don't cast the return value of `malloc()`. It is, at best, redundant, and may hide an error the compiler would catch otherwise. – pmg Jul 25 '14 at 15:54
  • 5
    [The curious pattern of pre-emptively rejecting the solution to your problem](http://blogs.msdn.com/b/oldnewthing/archive/2013/02/06/10391383.aspx) – chris Jul 25 '14 at 15:54
  • Perhaps a duplicate of http://stackoverflow.com/questions/2963898/faster-alternative-to-memcpy – Bill Lynch Jul 25 '14 at 16:12

3 Answers3

1

Try the following changes-

int buf[3] = {10, 20, 30};
int * send_buf = (int *)malloc(5 * sizeof(int));

*send_buf = 1;
for(i=1;i<=3;i++) // this will work for you. 
*(send_buf+i)=buf[i-1];
*(send_buf + 4) = 1;
Sathish
  • 3,740
  • 1
  • 17
  • 28
0

A simple implementation of memcpy() is:

memcpy(uint8_t *dest, uint8_t *src, size_t num_bytes) {
    for (size_t i=0; i<num_bytes; ++i)
        dest[i] = src[i];
}

So, since we can't use memcpy() for no good reason, let's just inline the body:

int buf[3] = {10, 20, 30};
int *send_buf = malloc(5 * sizeof(int));

send_buf[0] = 1;
send_buf[4] = 1;
for (int i=0; i<3; ++i)
    send_buf[i + 1] = buf[i];
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

Well, one can always do it with sprintf and sscanf

char buffer[1024];

sprintf(buffer, "%d %d %d", buf[0], buf[1], buf[2]);
sscanf(buffer, "%d%d%d", send_buf[1], send_buf[2], send_buf[3]);
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765