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 "="...
)
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 "="...
)
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.