array-1-ptr.c - A similar C program with pointers and dynamic allocation of memory - one dimensional. | Lecture 1 - slide 20 : 34 Program 5 |
#include <stdio.h> #include <stdlib.h> int main(void) { double *a = (double*)malloc(5 * sizeof(double)), sum = 0.0; int i, j, k; if (a == NULL){ printf("Memory allocation problem. Bye\n"); exit(EXIT_FAILURE); } for (i = 0; i < 5; i++) /* Initialize a */ *(a+i) = (double)(i + 1); *(a+1) = 2.2; /* a[1] = 2.2; */ for (i = 0; i < 5; i++) sum += *(a+i); printf("Sum = %f\n", sum); /* 15.2 */ free(a); return 0; }