0
#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 doesn't this code work?

and why does this code work?

void main(){
    int *i = (int *) malloc(12);
    i[0] = 1;
    printf("%d", i[0]);
}
LW001
  • 2,452
  • 6
  • 27
  • 36
  • 2
    If you open your C++ textbook and read the explanation of what the `[]` operator does, does your C++ textbook's explanation answer your question? Can you explain, in your own words, what "`*something[0]`" means, and how you believe this expression works? – Sam Varshavchik Aug 20 '23 at 21:15
  • @SamVarshavchik I'm not following any textbooks. You got any book recommendation? – John Persuro Aug 20 '23 at 21:34
  • https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Sam Varshavchik Aug 20 '23 at 21:38
  • 1
    To start with: [What compiler options are recommended for beginners learning C?](https://software.codidact.com/posts/282565) If you follow that advise, the compiler will point the 3 severe bugs/syntax errors in your code that makes this program invalid C. – Lundin Aug 21 '23 at 08:05

3 Answers3

1

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.

Sandrious
  • 118
  • 8
1

i[n] is a dereference. Equivalent to *(i + n).

i[0] has type int so you cannot dereference it: *i[n] is equivalent to **(i + n), and is invalid.

Cubic
  • 14,902
  • 5
  • 47
  • 92
Clifford
  • 88,407
  • 13
  • 85
  • 165
0

Why this code don't work?

    *i[0] = 1;

i is a pointer, so i[0] considers it (the pointer) to be a pointer to the start of an array, obtain the element at position 0 (the one you should assign) and assign it a 1 value. If you try to dereference it again, as the array element itself is not a pointer (but an integer value) you will get an error from the compiler. What you want to do is to use the array element itself

    i[0] = 1;

For the same reason, to print the array element, you need to use i[0] again and not the expression you used.

Why is this done with malloc()? Malloc is a general purpose dynamic memory allocator, it gathers a continous block of memory to fit the size you specify and returns to you a pointer to the result. You can then use that pointer as the address of the array you want to handle, or as a structure to be filled up with data.... etc. The void * pointer that malloc() returns can be converted to any other pointer type, making it flexible for any purpose.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31