How do I add something at the end of a C ++ array?

I have an array, but I want to add something to the end without overwriting any data that already represents it. It should be an array, not a vector, as that is the assignment.

+3


source to share


3 answers


From the comments, it sounds like you don't want to add to the end of the array, but partially fill the array and keep track of how much data you've written. You just need a variable to keep track of this:

char array[10];
size_t size = 0;

// Add characters:
array[size++] = 'H';
array[size++] = 'e';
array[size++] = 'l';
array[size++] = 'l';
array[size++] = 'o';

      



You need to make sure that you never go outside the array, otherwise you will damage other memory.

+10


source


C ++ arrays are not extensible. You need to either increase the size of the original array, or store the number of valid elements in a separate variable, or create a new (larger) array and copy the old content followed by the element (s) you want to add.



+4


source


You can create another array that is larger than the first and copy all the elements, then add the new element to the end of the array.

alternatively you can convert the array to a vector, add an element, and then convert the vector to an array back. Take a look at: How to convert a vector to an array in C ++ , What is the simplest way to convert an array to a vector? p>

+1


source







All Articles