0

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.

xp10r3r
  • 33
  • 5

2 Answers2

1

Instead of (pi+1) it should be (pi+i).

Sahil
  • 59
  • 11
1

After inserting 10 values the output is 6474931 which is I guess the initial value ?

Its because the variable sum is not initialized, default it contains some junk data due to automatic storage.

Initialize it with zero.

long sum = 0;

Also here

pi = (int *)malloc(10 * sizeof(int));

typecasting malloc() isn't necessary as malloc() return type is of void* type & it's safely converted to desired pointer type automatically. For e.g

pi = malloc(10 * sizeof(*pi));
if(pi == NULL) {
  /* @TODO error handling */
}

Do Read Do I cast the result of malloc?

Also here

scanf("%d", pi + 1);
sum += *(pi + 1);

you wanted to use pi + i as scanf("%d", pi + 1); every time scans data in same pi+1 memory location, other memory location like pi +2, pi + 3 .. pi + 9 are unused. So change it to

scanf("%d", pi + i);
sum += *(pi + i);

Sample code :

int main(void) {
    long sum = 0;
    int *pi = malloc(10 * sizeof(*pi));
    if(pi == NULL) {
        /* @TODO 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);
        sum += *(pi + i);
    }
    printf("\nSum of dynamic allocated memory: %ld", sum);
    free(pi);
    return 0;
}

O/p :

Please put in 10 values.

  1. Value: 1
  2. Value: 2
  3. Value: 3
  4. Value: 4
  5. Value: 5
  6. Value: 6
  7. Value: 7
  8. Value: 8
  9. Value: 9
  10. Value: 10

Sum of dynamic allocated memory: 55

Achal
  • 11,821
  • 2
  • 15
  • 37
  • Typecasting is required by the tutor, however, I'll keep it in mind that it's not necessarily needed. I found the error with 1 instead of i in the meanwhile as well. – xp10r3r May 01 '19 at 11:02