Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exercise: Using pointers cross-function in C Language returns error "invalid type argument of unary ‘*’ (have ‘int’)" [closed]

Tags:

c

pointers

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

I'm currently trying to resolve some exercises using C, to put in practice some stuff I've been studying recently, but I keep getting several distinct errors when using pointers, which I'm not being able to figure out by myself.

In this case I have this challenge from Hackerrank, and I was supposed to return the sum of all the array's elements, but I keep getting this compilation error in 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 it involves the use of pointers, but I'm not sure how to handle it. I've tried using int *sum = malloc(sizeof(int)); and *sum += *ar[i]; but the same error persists.

Any advices?

like image 997
Lucas Cazeto Avatar asked Jan 30 '23 23:01

Lucas Cazeto


2 Answers

It should not be *ar[i], it should just 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;
}
like image 53
sameera lakshitha Avatar answered Feb 01 '23 13:02

sameera lakshitha


The syntax *ar[i] is invalid given the declaration int *ar.

Because the expression ar[i] is equivalent to *(ar + i), the given expression is the same as *(*(ar + i)).

So you start with ar which is of type int *. Then *(ar + i) is of type int. So *(*(ar + i)) is invalid because you're attempting to dereference a non-pointer type.

ar[i] by itself is enough to get the array element, so that's what you use in your expression.

sum += ar[i];
like image 31
dbush Avatar answered Feb 01 '23 13:02

dbush