Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

#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]);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading