Difference between “char[] name” and “char name[]”

2020-05-09 09:31发布

When defining a function like this:

void  myFunction(arguments){
   // some instructions
}

what is the deference between using char[] name and char name[] as the function's argument. And why not use a pointer to char instead.

标签: c
3条回答
别忘想泡老子
2楼-- · 2020-05-09 09:36

In other languages such as Java and C#, the location of the [] brackets is just syntactic sugar and doesn't affect the program in any way.

C, being an older language, doesn't have that flexibility. An array must be declared with the brackets after the name.

As for when and why you would use a pointer instead, have a read here.

查看更多
走好不送
3楼-- · 2020-05-09 09:45

You will get compile error.

0.c:3:14: error: expected ‘;’, ‘,’ or ‘)’ before ‘a’
 int f(char []a){
              ^

It is impossible to compile a code like this:

#include <stdio.h>

int f(char []a){
}

main(){
}
查看更多
▲ chillily
4楼-- · 2020-05-09 09:48

The 1st one (char[] name) won't compile as it's the wrong syntax.

Array subcripts in definitions for the parameters of a function's implementation go to the name of (mandatory) parameter.

The correct syntax is the 2nd:

char name[]

Example:

void p(char[]); /* prototype */

void p(char name[]) /* implementation */
{
}

However char[] name will be considered invalid syntax.

查看更多
登录 后发表回答