while allocating/printing why don't I have to dereference an array pointer in c?

Advertisements
#include <stdio.h>

void main(){
    int *i = (int *) malloc(12);
    *i[0] = 1;
    printf("%d", *i[0]);
}

i is supposed to be a pointer. So then why doesnt this code work?

and why does this code 👇 work?

void main(){
    int *i = (int *) malloc(12);
    i[0] = 1;
    printf("%d", i[0]);
}

>Solution :

When you add index operator "[]" after a poitner – you are telling the compiler "Hey, take this pointer, then do pointer arithmetic on it with the value within the [] bracets, and dereference the address it points to".

Saying it with other words – when you add index operator "[]", your pointer gets treated as regular variable, and does not need additional dereferencing operator. It’s already dereferenced.

Leave a ReplyCancel reply