Is there a way to copy a whole smaller array into a section of a larger array? For example, if I have an array of 4 characters, and an array of 16, can I copy the 4 characters into the first 4 of the array of 16. Then another 4 characters to 4-7, etc. I know it's possible to do with a loop, but I was wondering if there was a way to do it otherwise. Here's the section of code that I'm trying to get to work.

int numtype = htons(5);
char type[4] = "";
_itoa_s(numtype, type, 4, 10);
message[0] = *type;

I need to convert the message to be sent byte by byte to a server with each 4 bytes containing control messages for the server. This is just one of the 4 of 16 bytes of the whole message.

Thanks Ancient Dragon,
That seemed to get rid of my runtime errors, but it still doesn't seem to be filling the array with the correct values. Could you take a look at how I'm doing it and tell me how it could be corrected?

int numtype = htons(5);
char type[sizeof(int)];
memcpy(type, (char *)&numtype, sizeof(int));
message[0] = *type;

int numseq = htons(sequence);
har seq[sizeof(int)];
memcpy(seq, (char *)&numseq, sizeof(int));
message[4] = *seq;

int nump1 = htons(0);
char p1[sizeof(int)];
memcpy(p1, (char *)&nump1, sizeof(int));
message[8] = *p1;

int nump2 = htons(0);
char p2[sizeof(int)];
memcpy(p2, (char *)&nump2, sizeof(int));
message[12] = *p2;

I should note the message is declared as char message[16] elsewhere in the program, and sequence is just a 4 digit number.

>>message[0] = *type;
how is message declared ? is it a character array ? Yes, then the above only copies the first byte to message. Why just memcpy to message instead of using a temporary array.

memcpy(message, (char *)&number, sizeof(int));
memcpy(&message[sizeof(int)], (char *)anotherNimber, sizeof(int));
// etc

Doing your previous example, I would still need to go through each index in the array, wouldn't I? Unless I'm just misunderstanding. What I ultimately want to do is take 4 bytes and put them in 0-3, 4 more bytes and put them in 4-7, then 8-11, then 12-15. Is the only way to do this byte by byte with memcpy or setting up a for loop?

>>Is the only way to do this byte by byte with memcpy or setting up a for loop?
There is one other way that I can think of *(int *)&message[0] = number;

int main()
{
    unsigned char message[4];
    int number = 1234;
    *(int *)&message[0] = number;
    cout << *(int *)message << "\n";
    return 0;
}
This article has been dead for over six months. Start a new discussion instead.