将字符串传递给C中的函数 - 带或不带指针? [英] Passing string to a function in C - with or without pointers?
问题描述
当我向函数传递一个字符串时,有时候会使用
char * functionname(char * string name [256 ])
有时我会在没有指针的情况下使用它(例如:
) char functionname(char string [256])
我的问题是,我什么时候需要使用指针?我经常编写没有指针的程序,它有效,但有时它不会。 方案
将C字符串传递给函数的公认方法是使用一个指针:
void function (char * name)
当函数修改字符串时,您还应该传入长度: p>
void function(char * name,size_t name_length)
你的第一个例子:
char * functionname(char * string name [256] )
传递一个指针数组到第二个例子:
<$> c $ c> char函数名(字符串[256])
传递一个字符数组。这里的数组大小并不重要,参数无论如何会衰减到指针,所以这相当于:
char functionname(char * string)
另见这个问题,以获取C中数组参数的更多细节。
When I'm passing a string to the function sometimes I use
char *functionname(char *string name[256])
and sometimes I use it without pointers (for example:
char functionname(char string[256])
My question is,when do I need to use pointers ? Often I write programs without pointers and it works,but sometimes it doesn't.
The accepted convention of passing C-strings to functions is to use a pointer:
void function(char* name)
When the function modifies the string you should also pass in the length:
void function(char* name, size_t name_length)
Your first example:
char *functionname(char *string name[256])
passes an array of pointers to strings which is not what you need at all.
Your second example:
char functionname(char string[256])
passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:
char functionname(char *string)
See also this question for more details on array arguments in C.
这篇关于将字符串传递给C中的函数 - 带或不带指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!