copying an Array

is there a way to copy the value of an array over to another?
1
2
3
4
5
6
7
8
9
int main() {
   int arraysrc[10];
   int arraydest[10]; //dest must be big enough to hold the data
   int i;
   for(i=0;i<10;i++) {
      arraydest[i]=arraysrc[i];
   }
   return 0;
}
Thats great, Thank you. would you just be able to explain the code, as i am still very knew to programming.

Thanks
Sure. The 'for' statement is what makes it all happen, assuming that 'arraydest[10]' is big enough to hold arraysrc.

With for, there are three different statements before the block of code even starts, these are all contained in the (). The first one is 'i=0'. This initiates your limiting variable. The second statement, 'i<10', is saying, "as long as 'i' is less then 10, do the code below." This is the test statement. The third, 'i++', is the increment statement. It says how much your limiting variable is changed. You can go up or down with this as much as you'd like.

Now that that's all set up, look to the code block.

arraydest[i]=arraysrc[i];

This simply assigns arraysrc to arraydest using 'i' as an array index. The for loop will loop all the way from 0 (the first index number for an array) to 9 (because if i==10, it will step outside the for statement).
Last edited on
The issues that can arise from this, is that you are assuming that 'arraydest' is 10 ints long. if arraysrc was 15 ints long, and arraydest was still 10, you run the risk of 'writing off of the end' of an array. So you should always ensure that your arrays are being used properly. For more information refer to the tutorial here: http://www.cplusplus.com/doc/tutorial/arrays/
Topic archived. No new replies allowed.