When I'm passing a string to the function sometimes I use
char *functionname(char *name[256])
and sometimes I use it without pointers (for example:
char functionname(char name[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.
In C, if you need to amend a string in a called function, pass a pointer to the first char in the string as an argument to the function. If you have allocated storage for the string outside the function, which you cannot exceed within the function, it's probably a good idea to pass in the size.
To pass a one dimensional string to a function as an argument we just write the name of the string array variable. In the following example we have a string array variable message and it is passed to the displayString function.
To pass a string by value, the string pointer (the s field of the descriptor) is passed. When manipulating IDL strings: Called code should treat the information in the passed IDL_STRING descriptor and the string itself as read-only, and should not modify these values.
C doesn't have strings as first class values; you need to use strcpy() to assign strings.
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 *name[256])
passes an array of pointers to strings which is not what you need at all.
Your second example:
char functionname(char name[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 *name)
See also this question for more details on array arguments in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With