Copying Arrays

Mar 9, 2014 at 6:08am
I am trying to copy the values from array 2 to array 1 however when I compile I get the error "string subscript out of range".

From what I understand this means that I went of of bounds on the index of my array. However I can't resolve this issue.

Any help would be appreciated.

1
2
3
4
5
6
string array1;
string array2;
for (int n = 0; n < elements; n++)
	{
			array1[n] = array2[n];
	}


In case you need a little more context...

"elements" represents the amount of elements to copy from beginning to end but
not the index #

array one will hold no values while it is likely that array two will hold values.
Last edited on Mar 9, 2014 at 6:13am
Mar 9, 2014 at 6:16am
if you are using std::string you can simply do array1 = array2; If you are however using a cstring you will need to make sure that the number of elements is within the range of the array you are copying to. You must also append a null-terminator at the end.

What it seems like you are trying to do is something like:

1
2
3
4
5
6
7
8
9
10
std::string array1 = "hello"; //size = 5
std::string array2 = "hi"; //size = 2

for(int i = 0; i < 5; ++i)
{
    array2[i] = array[i]; //array 2 is size of 2 so you will soon go out of bounds
}

//you should use this:
array2 = array1;


Mar 9, 2014 at 6:24am
Except im only trying to copy a range of elements, say the first 5 elements, so how could i go about doing that without going out of bounds.
Mar 9, 2014 at 6:32am
You must make sure the string you are copying to has room for it. There are several ways to do it. You could call the resize* method array2.resize(elements); then copy how you are. You could set the string to an empty one then append* the characters like:
1
2
3
4
5
array2 = "";

//loop
    array2 += array1[i];
//end loop 
You could use substr* function and assign that to the other string array2 = array1.substr(0,elements); There are other methods too but these should work for what you want.

Links that are possible solutions:

http://www.cplusplus.com/reference/string/string/resize/

http://www.cplusplus.com/reference/string/string/operator+=/
http://www.cplusplus.com/reference/string/string/append/
http://www.cplusplus.com/reference/string/string/push_back/
http://www.cplusplus.com/reference/string/string/insert/

http://www.cplusplus.com/reference/string/string/copy/
http://www.cplusplus.com/reference/string/string/substr/


http://www.cplusplus.com/reference/algorithm/copy/
Last edited on Mar 9, 2014 at 6:33am
Mar 9, 2014 at 6:37am
Thanks so much i just appended it like you said.
Topic archived. No new replies allowed.