Isn't i
in scanf
and in sum
useless? It doesn't change anything, even when I print &ptr
it doesn't show me any difference in memory values.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *)malloc(n * sizeof(int));
// if memory cannot be allocated
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for (int i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum = sum + *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}