I have an array, but I want to add something at the end without overwriting any of the data that is already present it it. It has to be an Array not a vector as it is an Assignment.
-
how do you define the array? are you using standard c? or std:: something or other? – thang Feb 04 '13 at 10:04
-
@thang I am not using std:: – Feb 04 '13 at 10:06
-
so like int x[100]? i think you should just post some sample code. there are so many ways in which you can do array... it's hard to tell what you're trying to do. – thang Feb 04 '13 at 10:08
-
@thang well, my array is x[10] characters long. – Feb 04 '13 at 10:09
-
@MokammelHossainSanju: You certainly can't extend it if it's a fixed-sized array like `x[10]`. You'll need to allocate your array dynamically with `new[]`; when it needs to grow, allocate a new one, copy the data over, and delete the old one. – Mike Seymour Feb 04 '13 at 10:17
-
@MikeSeymour What I meant was first 5 memory spaces of the array already have been assigned values, I will be adding more to it, but I always need that new data to be added at the end without overwriting any of the existing data – Feb 04 '13 at 10:20
-
well then just keep track of the # of bytes used... and as you write more to it, increase that counter. if you run off the end of the array, then crash... :p – thang Feb 04 '13 at 10:23
-
possible duplicate of [Adding something at the end of an Array?](http://stackoverflow.com/questions/14683373/adding-something-at-the-end-of-an-array) – jrok Feb 04 '13 at 10:35
3 Answers
From the comments, it sounds like you don't want to add to the end of an array, but rather to partially fill an array and keep track of how much data you've written. You just need a variable to keep track of that:
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 beyond the end of the array, otherwise you will corrupt other memory.

- 249,747
- 28
- 448
- 644
C++ arrays aren't extendable. You either need to make the original array larger and maintain the number of valid elements in a separate variable, or create a new (larger) array and copy the old contents, followed by the element(s) you want to add.

- 167,307
- 17
- 350
- 455
-
1actually I think my Question was wrong, my question should have been, "my array is 10 characters long. 5 of them have datas. I am going to put new datas in the array so that the new data is always added at the end of the array". – Feb 04 '13 at 10:18
You can create andother Array which is bigger than the 1st one and copy all elements then add the new element at the end of the array.
alternatively you can convert the array to vector, add an element then convert the vector to array back. Take a look at: How to convert vector to array in C++, What is the simplest way to convert array to vector?

- 1
- 1

- 36,908
- 70
- 97
- 130