I've a question similar to this one: Assigning char array of pointers with scanf
Rather of assigning char values to an array of pointers I'd like to assign values to int of pointers with scanf. In the following example I'd assign 10 int values and that's the reason why it's hard-coded.
void main(void) {
int *pi;
long sum;
pi = (int *)malloc(10 * sizeof(int));
if(pi == NULL)
/* Error Handling */
printf("\n\nPlease put in 10 values.\n\n");
for(int i = 0; i < 10; i++) {
printf("%d. Value: ", i + 1);
scanf("%d", pi + i);
/* It was scanf("%d", pi + 1) in previous version. */
sum += *(pi + i);
/* Same issue, it was sum += *(pi + 1) in the previous version. */
}
printf("\nSum of dynamic allocated memory: %ld", sum);
free(pi);
}
After inserting 10 values the output is 6474931 which is I guess the initial value. Any idea what I'm doing wrong?
Thanks for any help which is much appreciated.