Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast elements during copying

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;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading