Hi, I am probably blind or lacking some basic knowledge here but I cant seem to find a nice solution for copying a defined range from one (char*) array to another.
I want to split a char array in multiple small arrays.
For example I have a large array char* bigArray = newchar[500]; and I want to split it in multiple parts for whatever reason, in an array like this char* splitArray = newchar[100];.
So for the first run I would copy the content of bigArray from [0] to [99] into splitArray, the second run is [100] to [199] until the final run from [400] to [499].
The most obvious solution is to copy one character after another from one array to another (which I am currently doing) but I am sure there has to be a more efficient solution to immediately copy the whole memory range and not every single char but apparently I am too stupid to find it...
I already found memcpy or strncpy but it seems to me that they always start from the beginning of the source array or?
Another found was strtok but this splits the string only up to certain characters so also not usable for this.
I hope you can point me in the right direction here, thanks ;)
Don't use strcncpy, that stops when it encounters zero. You ultimately use memcpy. It's your job to pass in the correct range. STL provides copy that takes iterators.
Sorry but could you perhaps post an example what the code would look like here? Because I have trouble to correctly use memcpy here.
The function takes 3 parameters as described in the documentation:
1) destination
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
2) source
Pointer to the source of data to be copied, type-casted to a pointer of type void*.
3) num
Number of bytes to copy.
1) destination is obvious, simply the array I where I want to store the content (in my example splitArray).
2) source is also self-explanatory but wouldn't this always start copying from the beginning of the source array [0] or am I missing something here?
3) num is the range of bytes I want to copy, if I pass 100 for example it would copy the content from source from 0 to 100 right?
2) bigArray is a pointer to the first element, bigArray[0] is the data it points to.
pointers are just numbers, they represent memory id numbers. you can add and subtract pointers and this will result in the pointer pointing to something else. So (bigArray + 100) points to bigArray[100].
3) almost true, it will copy 100 bytes. So it will copy element 0 to 99 (not 100).