|
Salem (Programmer) |
30 Sep 06 3:31 |
> I am repeatedly copying the array elements from old array to new array, > performing operations on the new array (changing) in the process and then > determining whether or not use the new array values or the old ones. Consider this CODE#include <stdio.h> #define ROWS 10 #define COLS 20
typedef int (*twod_ptr)[COLS];
void clear ( twod_ptr arr ) { int r,c; for ( r = 0 ; r < ROWS; r++ ) { for ( c = 0 ; c < COLS; c++ ) { arr[r][c] = 0; } } }
int calc ( twod_ptr old_a, twod_ptr new_a ) { printf( "old_a=%p new_a=%p\n", (void*)old_a, (void*)new_a ); new_a[0][0] = old_a[0][0] + 1; return new_a[0][0]; }
void swap_arrays ( twod_ptr *p1, twod_ptr *p2 ) { twod_ptr temp = *p1; *p1 = *p2; *p2 = temp; }
int main ( ) { int array1[ROWS][COLS], array2[ROWS][COLS]; twod_ptr old_a = array1; twod_ptr new_a = array2; int result, i;
printf( "Array1 at %p, array2 at %p\n", (void*)array1, (void*)array2 ); printf( "old_a at %p, new_a at %p\n", (void*)old_a, (void*)new_a );
clear( old_a ); clear( new_a );
for ( i = 0 ; i < 10 ; i++ ) { old_a[0][0] = i; result = calc( old_a, new_a ); if ( result % 2 == 0 ) { printf("Result - swapping\n" ); swap_arrays( &old_a, &new_a ); } }
return 0; } Not a malloc() or a memcpy() to be seen. The arrays themselves don't move, all that changes are the two pointers to the start of each 2D array. The whole thing is exchanged with 3 simple pointer assignments. My results $ ./a.exe Array1 at 0x22c9c0, array2 at 0x22c6a0 old_a at 0x22c9c0, new_a at 0x22c6a0 old_a=0x22c9c0 new_a=0x22c6a0 old_a=0x22c9c0 new_a=0x22c6a0 Result - swapping old_a=0x22c6a0 new_a=0x22c9c0 old_a=0x22c6a0 new_a=0x22c9c0 Result - swapping old_a=0x22c9c0 new_a=0x22c6a0 old_a=0x22c9c0 new_a=0x22c6a0 Result - swapping old_a=0x22c6a0 new_a=0x22c9c0 old_a=0x22c6a0 new_a=0x22c9c0 Result - swapping old_a=0x22c9c0 new_a=0x22c6a0 old_a=0x22c9c0 new_a=0x22c6a0 Result - swapping --
|
|