繁体   English   中英

截断数组的最后几个元素

[英]Truncate the last few elements of an array

我是 C 和 C++ 的新手,请帮助我获得所需的解决方案。 我使用 memcpy 将“array”的内容复制到“arr”。 但由于 'arr' 的大小为 10,它会将 0 附加到其余元素。 如何将“arr”截断为 5。

#include <iostream>

#include <string.h>

using namespace std;

int main()

{
    uint8_t array[5] = {1,2,3,4,5};

    uint8_t arr[10] = {0};

    memcpy( arr, array, 5);

    for (auto e: arr){

        cout << e << " ";

    }

    return 0;    
}

Output 为上述代码: 1 2 3 4 5 0 0 0 0 0

需要 output:1 2 3 4 5

编译后不能截断 static 数组的大小。 如果您使用其他一些数据结构,例如来自 C++ STL 的向量,那么该容器 object 的大小可能是可变的。

代替

for (auto e: arr){

    cout << e << " ";

}

您可以将数组的大小保存在一个变量中并 cout arr 那次,例如:

int i, arraySize = 5;

for (i=0; i<arraySize; i++) {

    cout << arr[i] << " ";

}

Best Practice is to create a pointer and free the memory or second way is to don't allow kernel to give memory to you create custom memory allocator and assign it to your array

暂无
暂无

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

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