0

How can i split one array char to two another array char? for example :

char array1[9]={10011010}; char array2[5],array3[5];

now i want put 1001 in array2 and 1010 in array3 how can i this request?

3 Answers 3

1

Many ways. Two that come to mind are memcpy and std::copy.

#include <cstring>
memcpy(array2, array1, 4);
memcpy(array3, array1+4, 4);

or

#include <algorithm>
std::copy(array1, array1+4, array2);
stdd::copy(array1+4, array1+8, array3);

It seems from your array sizes that you keep one more byte than you need. Perhaps these are character strings, in addition to being simple arrays? If so, please remember to put a null byte at the end of the arrays before you use them:

array2[4] = 0;
array3[4] = 0;
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a for loop, memcpy or STL's copy algorithm.

Comments

0

Well, your first array is 9 chars. If you split it into two, one must be 5 and one must be 4 chars. This should do the trick:

char array1[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // not a null-terminated string
int len = sizeof(array1)/sizeof(array1[0]);
int len1 = len / 2;
int len2 = len - len1;
char* array2 = new char[len1];
char* array3 = new char[len2];

memcpy(array2, array1, len1);
memcpy(array3, array1 + len1, len2);

2 Comments

There's a memory leak if the second new throws.
of course, but that was not the point here. I'm pretty sure you can find problems like that in most of the samples people post on web. you can use std::vector for instance and not care about allocating memory, and you don't get into such problems there; my sample was a quick reference to one possible solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.