简体   繁体   English

在复制过程中铸造元素

[英]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.我刚刚解决了一个 C 任务,现在想知道是否有一种在转换数据类型时复制数组的快速方法。 Specifically, I had an array of integer values and wanted to copy this into a new array with long long int values.具体来说,我有一个包含 integer 个值的数组,我想将其复制到一个包含 long long int 值的新数组中。 The function memcpy copies only bytes without considering data types. function memcpy 只复制字节而不考虑数据类型。 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;
    }
}

memcpy assumes that the source and destination have compatible types, so it won't work here. memcpy假定源和目标具有兼容的类型,因此它在这里不起作用。 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.话虽这么说,这里的代码会按照您的要求执行(除了它应该自然地说arr[j] ),尽管强制转换严格来说不是必需的,因为 integer 将在赋值期间转换为左操作数的类型。

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.尽管如前所述,最好的优化是首先选择正确的类型,然后不要复制任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM