I just solved a C task and now wonder if there is a quick way to copy an array while casting the data type. Specifically, I had an array of integer values and wanted to copy this into a new array with long long int values. The function memcpy copies only bytes without considering data types. I have now solved this with a loop and wonder if there is a faster way.
void myfunction(int arr_count, int* arr) {
long long int arr_max[arr_count];
long long int arr_min[arr_count];
for(int j = 0;j < arr_count; j ){
arr_max[j] = (long long int) *arr;
arr_min[j] = (long long int) *arr;
}
}
CodePudding user response:
memcpy
assumes that the source and destination have compatible types, so it won't work here. I'm not quite sure why you wish to change the type on the fly during run-time - it is more sensible to use the most suitable type to begin with.
That being said, the code here does what you ask (except it should naturally say arr[j]
), although the cast is strictly speaking not necessary, since the integer will get converted to the type of the left operand during assignment.
You can't really optimize this code further without a specific system and use-case in mind. Though as already mentioned, the best optimization is to pick the correct type to begin with and then don't copy a thing.