-1

I am new to C and C++, please help me in getting the required solution. I have used memcpy to copy the contents of 'array' to 'arr'. But since the size of 'arr' is 10, it appends 0 to the remaining elements. How can I truncate the 'arr' to size 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 for the above code: 1 2 3 4 5 0 0 0 0 0

required output : 1 2 3 4 5

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Beginner
  • 73
  • 3
  • 2
    `uint8_t arr[10];` means you have always 10 elements... you might consider some value as sentinel, or use extra size parameter... or use `std::vector`. – Jarod42 Mar 24 '21 at 12:03
  • You cannot "truncate" a C-style array. Its size is declared when it's created and it will have this size until it is destroyed. – Yksisarvinen Mar 24 '21 at 12:04
  • "_But since the size of 'arr' is 10, it appends 0 to the remaining elements._" No, it doesn't. `arr` always have 10 elements. You cannot change the size of the array in C++ after the declaration of said array. – Algirdas Preidžius Mar 24 '21 at 12:05
  • If this is not a homework question, then I recommend avoiding C style arrays and instead use `std::vector`. Avoid `using namespace std;` always. Avoid `std::memcpy`, instead use [`std::copy`](https://en.cppreference.com/w/cpp/algorithm/copy). And you'll need `static_cast(e)` on the output, or you might get non-printing ASCII control characters on some platforms. – Eljay Mar 24 '21 at 12:17

3 Answers3

3

You cannot truncate the size of the static array after compilation. If you were using some other data structure like vector from C++ STL then the size of that container object might have been variable.

Parvinder Singh
  • 1,737
  • 2
  • 12
  • 17
0

Instead of

for (auto e: arr){

    cout << e << " ";

}

you can keep array's size in a variable and cout arr that times, like:

int i, arraySize = 5;

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

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

}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
-2

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

  • I think you mean the right thing, but your description is very unclear. Maybe some code would be helpful. Anyway, pointers and "best practice" don't go well together in modern C++. – Lukas-T Mar 24 '21 at 13:15