Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string as an argument in C

Tags:

c++

c

unix

pointers

I am having a function:

int getparam(char *gotstring)

and i am passing a string argument to it, like char *sendstring = "benjamin"

Instead of the above declaration I can use,

int getparam(char gotstring[])

Question: Which one is better? And if I have to use int getparam(char gotstring[]) what are all the other changes I have to make to the existing function?

like image 760
Vijay Avatar asked Dec 04 '09 11:12

Vijay


2 Answers

int getparam(char gotstring[]) and int getparam(char* gotstring) are identical. Personally, I would recommend the latter syntax, because it better describes what is actually going on. The getparam function only has a pointer to the string; it has no knowledge about the actual array size. However, that is just my opinion; either will work.

like image 175
Charles Salvia Avatar answered Oct 27 '22 16:10

Charles Salvia


The best way to accept a string argument is

int getparam(const char *gotstring);

You can then call this using a literal string:

int main(void)
{
  int x = getparam("is this a parameter string?");
  return 0;
}

Or a character array:

int main(void)
{
  char arg[] = "this might be a parameter string";
  int x = getparam(arg);
  return 0;
}

The use of const on the argument pointer indicates to the caller that the argument is read-only inside the function, which is very nice information.

like image 44
unwind Avatar answered Oct 27 '22 14:10

unwind