Exercise: Using pointer cross functions in C returns "invalid unary type argument" * (has "int")

I'm new here, so sorry if this post is not being edited properly.

I am currently trying to resolve some exercises with C to put into practice some of the things I learned recently, but when using pointers I get a few different errors that I cannot figure out myself.

In this case, I have this call from Hackerrank and I had to return the sum of all the elements of the array, but I keep getting this compilation error on line 12: invalid type argument of unary β€˜*’ (have β€˜int’)

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int simpleArraySum(int ar_size, int* ar) {
    int sum = 0;
    for (int i = 0; i < ar_size; i++){
        sum += *ar[i];                     //line 12
    }
    return sum;
}

int main() {
    int n; 
    scanf("%i", &n);
    int *ar = malloc(sizeof(int) * n);
    for(int ar_i = 0; ar_i < n; ar_i++){
       scanf("%i",&ar[ar_i]);
    }
    int result = simpleArraySum(n, ar);
    printf("%d\n", result);
    return 0;
}

      

I know this has to do with the use of pointers, but I'm not sure how to handle this. I tried using int *sum = malloc(sizeof(int));

and *sum += *ar[i];

but the same error persists.

Any advice?

+3


source to share


3 answers


It shouldn't be *ar[i]

, it should be ar[i]

.



int simpleArraySum(int ar_size, int* ar) {
    int sum = 0;
    for (int i = 0; i < ar_size; i++) {
        sum += ar[i];              
    }
    return sum;
}

      

+5


source


The syntax is *ar[i]

invalid given the declaration int *ar

.

Since expression is ar[i]

equivalent *(ar + i)

, this expression is the same as *(*(ar + i))

.

So you start with ar

, which is of type int *

. Then *(ar + i)

has a type int

. Therefore it *(*(ar + i))

is wrong because you are trying to dereference a non-pointer type.



ar[i]

by itself is enough to get an element of the array, so you use it in your expression.

sum += ar[i];

      

+2


source


As said in the comments, when s ar

is an array int

, you can access its elements like ar[0]

, ar[1]

etc.


You are confused between *ar

and ar[...]

.

This is because type int*

can mean:

  • a pointer to int

    , in which case you usually write *ar

    ;
  • an array of int

    s, in which case you would normally write ar[0]

    .

Side note (may get confusing): ar[0]

and *ar

both do the same, they return data by address ar

.

+1


source







All Articles