c - Combine or merge 2 array with loop or function -
i'm new c world. i'm using visual 2010. need create array 2 other arrays, or function merge them; come php i'm sorry if stupid. tested loop without success..
a real example helpful:
int arraya[5] = {3,2,1,4,5} int arrayb[5] = {6,3,1,2,9}
and printed expected output of third arrayc should :
arrayc { [3][6] [2][3] [2][1] [4][2] [5][9] }
a straightforward approach can following way
#include <stdio.h> #define n 5 int main( void ) { int a[n] = { 3, 2, 2, 4, 5 }; int b[n] = { 6, 3, 1, 2, 9 }; int c[n][2]; ( size_t = 0; < n; i++ ) { c[i][0] = a[i]; c[i][1] = b[i]; } ( size_t = 0; < n; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] ); return 0; }
the program output is
3, 6 2, 3 2, 1 4, 2 5, 9
if want write function merge arrays of size can like
#include <stdio.h> #include <stdlib.h> #define n 5 int ** merge( int *a, int *b, size_t n ) { int **c = malloc( n * sizeof( int * ) ); if ( c != null ) { size_t = 0; ( ; < n && ( c[i] = malloc( 2 * sizeof( int ) ) ); i++ ) { c[i][0] = a[i]; c[i][1] = b[i]; } if ( != n ) { while ( i-- ) free( c[i] ); free( c ); c = null; } } return c; } int main( void ) { int a[n] = { 3, 2, 2, 4, 5 }; int b[n] = { 6, 3, 1, 2, 9 }; int **c; c = merge( a, b, n ); if ( c != null ) { ( size_t = 0; < n; i++ ) printf( "%d, %d\n", c[i][0], c[i][1] ); ( size_t = 0; < n; i++ ) free( c[i] ); free( c ); } return 0; }
the program output same shown above.
Comments
Post a Comment