简体   繁体   中英

Passing string as an argument in C

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?

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.

In this case they mean the same thing, and you do not need to change the remainder of your function. But be aware that in general, arrays and pointers are different things.

Neither is better, really. It's what you're more comfortable with. Idiomatically, it is more common to use char *arg instead of char arg[] (think strcmp, strcpy, etc).

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.

Since arrays are sent by reference in C both

int getparam(char *gotstring)

and

int getparam(char gotstring[])

means the same. But first one is used more. So using it makes you a good C citizen.

This is called passing by reference and how the name states it means to pass just a reference of the variable (in this case a char* ).

Either solutions will work fine, what will actually happen is that, when void functionName(char* string) is called, the address of the first char in memory will be saved on stack and passed as a parameter to the function.

Consequently any edit to the variable inside the function would edit also the original variable. In this case, since you need to pass an array you just have this option.

For standard types like int , float you can distinguish them:

void passByValue(int i);
void passByReference(int &i);

The difference is that in the former case value is copied into stack when calling the function, while in the latter just a reference (pointer) to the value is passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM