What are the differences between (in C)
int * a
int [] a;
Where suppose we did int * a = malloc(...)
Isn't the second one also a pointer?
What are the differences between (in C)
int * a
int [] a;
Where suppose we did int * a = malloc(...)
Isn't the second one also a pointer?
As it stands right now, the second is simply a syntax error. The closest you could do would be int a[];
Even that, however, it's allowed--for a variable definition, the brackets need to contain a constant expression with a strictly positive value.
For a function parameter, int a[]
would be allowed, and so would something like int a[3]
. In this case, the two are precisely equivalent--when you define a function parameter with a type array of T
, it is adjusted to a type pointer to T
.
You can also do an extern declaration:
extern int *a;
extern int b[];
In this case, the two are actually both syntactically valid, but the results are different--you're declaring that a
has type pointer to int
, while b
has type array of int
.
If you evaluate the name of an array in an expression, it will usually yield the address of the first element of that array (though there are a few exceptions, such as when used as the argument to sizeof
). The array itself doesn't have that type though--what you're looking at is at least similar to an implicit conversion, somewhat similar to 2 + 10.0
, converting the 2
to a double
before doing the addition--2
itself is an int
, but in this expression, it's silently converted to double
.
I think you mean the difference between the following declarations
int a[N];
and
int *a = malloc( N * sizeof( int ) );
where N
is some integer value.
The first one declares an array with the static or automatic storage duration. The second one does two things. Its initializing expression allocates dynamically memory that can be occupied by an array with N
elements of type int
. And the address of the extent of memory is assigned to the pointer a
.
The allocated memory should be freed by the user when it is not needed any more.
So in the first declaration there is declared an object of type int[N]
while in the second declaration there is declared an object of type int *
. Correspondingly the size of the first object is equal to sizeof( int[N] )
that is equivalent to N * sizeof( int )
while the size of the second object is equal to sizeof( int * )
.
Pointers do not possess the information about whether they point to a single object or the first object of an array. So the user should hold the number of elements of the allocated array himself while for an array it can get the number by using expression sizeof( a ) / sizeof( *a )
.