arrayscpointerserror-handlingdereference

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


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.


Solution

  • 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.