is char a[64][]
equivalent to char *a[64]
?
If yes, what if I want to declare char a[][64]
using a single pointer. How can i do it?
is char a[64][]
equivalent to char *a[64]
?
If yes, what if I want to declare char a[][64]
using a single pointer. How can i do it?
char a[][64]
is similar in pointer representation to
char (*a)[64]
you can read this. for 2D-array the second dimension size should be specified.
You're looking for a pointer to an array:
char (*a)[64];
Perhaps you are not sure about how the following two statements are different.
char* a[64];
char (*a)[64];
The first one defines a
to be an array of 64
char*
objects. Each of those pointers could point to any number of char
s. a[0]
could point to an array of 10
char
s while a[1]
could point to an array of 20
char
s. You would do that with:
a[0] = malloc(10);
a[1] = malloc(20);
The second one defines a
to be a pointer to 64
chars. You can allocate memory for a
with:
a = malloc(64);
You can also allocate memory for a
with:
a = malloc(64*10);
In the first case, you can only use a[0][0]
...a[0][63]
. In the second case, you can use a[0][0]
... a[9][63]
char a[64][]
is equivalent tochar *a[64]
.
No, because char a[64][]
is an error. It attempts to define a
to an array of 64
elements where each element is of type char[]
- an incomplete type. You cannot define an array of elements of incomplete type. The size of element must be a fixed known constant. The C99 standard §6.7.5.2 ¶2 says
The element type shall not be an incomplete or function type.
Now if you were to compare char a[][64]
and char *a[64]
, then again they are different. That's because the array subscript operator has higher precedence than *
.
// declares an array type a where element type is char[64] -
// an array of 64 characters. The array a is incomplete type
// because its size is not specified. Also the array a must have
// external linkage.
extern char a[][64];
// you cannot define an array of incomplete type
// therefore the following results in error.
char a[][64];
// however you can leave the array size blank if you
// initialize it with an array initializer list. The size
// of the array is inferred from the initializer list.
// size of the array is determined to be 3
char a[][2] = {{'a', 'b'}, {'c', 'd'}, {'x', 'y'}};
// defines an array of 64 elements where each element is
// of type char *, i.e., a pointer to a character
char *a[64];
If you want to declare a pointer to an array in a function parameter, then you can do the following -
void func(char a[][64], int len);
// equivalent to
void func(char (*a)[64], int len);
char (*a)[64]
means a
is a pointer to an object of type char[64]
, i.e., an array of 64
characters. When an array is passed to a function, it is implicitly converted to a pointer to its first element. Therefore, the corresponding function parameter must have the type - pointer to array's element type
.