Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string to a function in C - with or without pointers?

Tags:

c

function

string

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.

like image 632
Zen Cicevic Avatar asked Jun 16 '13 09:06

Zen Cicevic


People also ask

How do you pass a string to a function in C?

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.

Can you pass a string into a function?

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.

How do you pass strings?

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.

Can you pass a string by value in C?

C doesn't have strings as first class values; you need to use strcpy() to assign strings.


1 Answers

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.

like image 98
Adam Zalcman Avatar answered Sep 20 '22 13:09

Adam Zalcman