Monday, July 27, 2009

C question on arrays and pointers...?

I have two arrays array1[10] and array2[10] of type int. I want to copy the value of array2[10] into array1[10] within an infiite loop


for(;;)


{





for(i=0;i%26lt;10;i++)


array1[i] = array2[i]





}





but the actual array I am using has a large number of values and I want to use to pointers to just change the memory location the array points to , instead of copying the whole array1[] value , how can I do that?[

C question on arrays and pointers...?
My knowledge of C is a bit rusty but let me see if you only copy the pointer you will access the same data in memory as the original pointer. A pointer is like a home address if you make a copy of it, it still takes you to the same home. So you are not making a new instance of the variable in the memory.


There are always easier ways of doing stuff you only need to think about them.
Reply:You cannot change the base address of an array. So whatever you are asking is strictly not possible.





Another smarter way of doing it is to use integer pointers instead of integer arrays. declare two pointers





int *array1, *array2;





allocate memory to array 1 and fill the data in it





array1=(int *) malloc(N*sizeof(int));





for copying, just do





array2=array1;





This is not possible if u declare array1 and array2 as strict arrays


No comments:

Post a Comment