Curso de Programación en C/Prog78
Ir a la navegación
Ir a la búsqueda
Prog78
1 #include <stdio.h>
2
3 #define COLS 4
4
5 int sum2d( int ar[][COLS], int filas );
6 int sum( int ar[], int n );
7
8 int main(void)
9 {
10 int * pt1,
11 (*pt2)[COLS],
12 total1,
13 total2,
14 total3;
15
16 pt1 = (int [2]) {10, 20}; // compound literales
17 pt2 = (int [2][COLS]) { {1,2,3,-9}, {4,5,6,-8} };
18
19 total1 = sum( pt1, 2 );
20 total2 = sum2d( pt2, 2 );
21 total3 = sum( (int []) {4,4,4,5,5,5}, 6 );
22 printf( "total1 = %d\n", total1 );
23 printf( "total2 = %d\n", total2 );
24 printf( "total3 = %d\n", total3 );
25
26 return 0;
27 }
28
29 int sum( int ar[], int n )
30 {
31 int i;
32 int total = 0;
33
34 for( i = 0; i < n; i++)
35 total += ar[i];
36
37 return total;
38 }
39
40 int sum2d( int ar[][COLS], int filas )
41 {
42 int r;
43 int c;
44 int tot = 0;
45
46 for( r = 0; r < filas; r++ )
47 for( c = 0; c < COLS; c++ )
48 tot += ar[r][c];
49
50 return tot;
51 }
Resultado
[rrc@Pridd CClase]$ gcc -Wall -O2 -o Prog78 Prog78.c [rrc@Pridd CClase]$ ./Prog78 total1 = 30 total2 = 4 total3 = 27 [rrc@Pridd CClase]$ === Explicación ===