What is the difference between char str[] and char *str as function parameters?

荒凉一梦 提交于 2020-01-16 03:40:07

问题


Say we have the following function prototypes:

void function1(char str[]);
void function2(char *str);

Now say we have a string char name[] = "John"; that we wish to pass through these functions. What is the difference between the two? What are their uses and limitations? Are there circumstances in which one is preferred over the other? Would it make a difference if instead the string were initialized as char *name = "John"?

I understand the difference between using char str[] and char *str within a function, but I don't know their behavior as function parameters or arguments.


回答1:


There is absolutely no difference in C between

void function1(char str[]);
void function2(char *str);

because char str[] simply reduces to char * when passed as argument to a function.And for the record, even char str[20] is exactly the same thing as the function sees it as char *str.

As for whether it would make a difference if the string were initialized as

char *name = "John";

yes,it does!Here address of that string John is being assigned to pointer name, and another addresses can be reaassigned to name later.

char *name="John";
name="Mary";  //Works in C

But in

char name[]="John";

you are initializing a character array object name to John.The difference here is that you just can't reassign another string to name after initialization.The following is wrong in C:

char name[]="John";
name="Mary";// Wrong

While posting questions,search the forum for a minute to see if the question has already been answered.The first part of your question has been asked and answered very well multiple times.Since you seemed genuinely confused about the second part,I've answered that here.




回答2:


There is no difference. Inside a parameter list, parameters of the form T[] and T[n] are silently re-written as T* by the compiler. This means that you cannot pass arrays by value.




回答3:


There is no difference from a technical point of view. However, if you use [] then you are documenting for the person reading your code that you expect an array.



来源:https://stackoverflow.com/questions/16258075/what-is-the-difference-between-char-str-and-char-str-as-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!