When you use the type char x[]
instead of char *x
without initialization, you can consider them the same. You cannot declare a new type as char x[]
without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers.
When you use the type char x[]
instead of char *x
with initialization, they are completely 100% different.
Example of how char x[]
is different from char *x
:
char sz[] = "hello";
char *p = "hello";
sz
is actually an array, not a pointer.
assert(sizeof(sz) == 6);
assert(sizeof(sz) != sizeof(char*));
assert(sizeof(p) == sizeof(char*));
Example of how char x[]
is the same as char *x
:
void test1(char *p)
{
assert(sizeof(p) == sizeof(char*));
}
void test2(char p[])
{
assert(sizeof(p) == sizeof(char*));
}
Coding style for passing to functions:
It really doesn't matter which one you do. Some people prefer char x[]
because it is clear that you want an array passed in, and not the address of a single element.
Usually this is already clear though because you would have another parameter for the length of the array.
Further reading:
Please see this post entitled Arrays are not the same as pointers!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…