Why do I get the error when I try to dereference a pointer to an array?

83 Views Asked by At

I'm very basic at C and I don't understand something along these codes. In the first piece of code I am declaring an array called arr with predefined values and I also declare a pointer of type int called p. After that I'm pointing to the first element of arr and I print the value to what p points to. Everything understood so far.

#include <stdio.h>

int main(void)
{
    int arr[5] = {10, 20, 30, 40, 50};
    int *p;

    p = &arr[0];  

    printf("%d\n", *p); // prints 10
}

But then I want to use this function and what bothers me is do I need to dereference the pointer a or not? Do I have to write a[index] * 2 or *a[index] * 2? If I write the second case I get an error.

void multiply(int *a, int length)
{
    for (int index = 0; index < length; index++)
        printf("%d\n", a[index] * 2);
}

Error:

error: invalid type argument of unary ‘*’ (have ‘int’)
    6 |         printf("%d\n", *a[index] * 2);

I don't really understand so please kindly shed some light :)

I searched the internet but I'm a beginner at this and don't know exactly how pointers work.

2

There are 2 best solutions below

1
Eric Postpischil On BEST ANSWER

The subscript operator, [ … ], includes a dereference, *.

a[index] is defined to be *(a + index), meaning to take the pointer a, calculate the address for index elements beyond it, and then dereference that new pointer.

0
persona On

While indexing the elements of the array, you actually don't need dereferencing the array elements since the array elements are not references to the array elements but rather the values the array stored in the first place.

to Multiply function you send the address of the first element with

multiply(&arr[0], 5)

since it's an array, the function call above is the same with

multiply(arr, 5)

this sends the multiply function the first address of the arr array already.

So, dereferencing inside the multiply function will result an error because array indexes don't store the address of the array elements but rather values. So you've been making dereferencing on the values of the array elements, something like arr[index] is valid but not the other way around.