Zen Cicevic Zen Cicevic - 3 years ago 84
C Question

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download