-4

What is the difference between * and [] in variable declarations in C?

I thought they were the same but this code compiles: int values[] = {1, 2 ,3};
And this one int values* = {1, 2, 3}; causes a parsing error. (expected one of "="...)

Anthony
  • 644
  • 7
  • 23
  • I doubt this `int values* = ...` compiles. – alk Nov 18 '13 at 11:22
  • You'll need to read a beginner C book if you have questions about syntax. –  Nov 18 '13 at 12:21
  • @Dean, I know the difference between arrays and pointers, I thought that `[]` and `*` were syntactically equivalent (i'm talking about square braces without a value inside). – Anthony Nov 18 '13 at 12:30

1 Answers1

1

They are the same in some way, but they are not equivalent. Firstly, you showed there a initialisation. A pointer is basically a variable which has as value a memory adress. So you can not use initializers like this one int values* = {1, 2, 3};

Secondly, when you access some array with a[5], this is translated into a dereference of a memory adress: *(a+5). Also, the name of an array is a pointer to the first element.

Of course, there are many more things to be said. I tried to give you a glimpse of what is going on, but I suggest you reading a C book.

To conclude, [] is just an operator that allows us to use arrays without having to use complicated pointer arithmetic. Its functionality can be replaced with pointers, but the syntax and the way you actually do it is very different, and, in most cases, not necessary.

Paul92
  • 8,827
  • 1
  • 23
  • 37