#include #include #include int main () { int A[10]; // Statically-sized unidimensional array. double B[20][20]; // 2D array. int *A2 = NULL; // Declaration of 1D array variable. double **B2 = NULL; // Declaration of 2D array variable. int i, j; // For-loop variables. int sum; // For use in examples. double dSum; // Static example. The space is already allocated, so the // array can be used immediately. for (i=0; i < 10; i++) { A[i] = i * 100; // Fill the array with some numbers. } sum = 0; for (i=0; i < 10; i++) { sum += A[i]; // Compute the sum of array's numbers. } printf ("sum = %d\n", sum); // Print sum. // Dynamic version of example using "malloc" to allocate space. // Note the use of the "sizeof" keyword. A2 = (int*) malloc (sizeof(int) * 10); for (i=0; i < 10; i++) { A2[i] = i * 100; // Fill the array with some numbers. } sum = 0; for (i=0; i < 10; i++) { sum += A2[i]; // Compute the sum of array's numbers. } printf ("sum = %d\n", sum); // Print sum. // 2D example with static array. for (i=0; i < 20; i++) { for (j=0; j < 20; j++) { B[i][j] = i*j; // Fill the array with some numbers. } } dSum = 0; for (i=0; i < 20; i++) { for (j=0; j < 20; j++) { dSum += B[i][j]; // Compute the sum of array's numbers. } } printf ("dSum = %lf\n", dSum); // Print sum. // Dynamic version of 2D example. Note the two-step allocation. // Allocate space for 20 pointers-to-double B2 = (double **) malloc (sizeof(double*) * 20); for (i=0; i < 20; i++) { // For each such pointer, allocate a size-20 double array. B2[i] = (double*) malloc (sizeof(double) * 20); } for (i=0; i < 20; i++) { for (j=0; j < 20; j++) { B2[i][j] = i*j; // Fill the array with some numbers. } } dSum = 0; for (i=0; i < 20; i++) { for (j=0; j < 20; j++) { dSum += B2[i][j]; // Compute the sum of array's numbers. } } printf ("dSum = %lf\n", dSum); // Print sum. // Must free allocated memory when not needed anymore: free (A2); free (B2); }