Can C function parameters set variables?

徘徊边缘 提交于 2020-01-17 04:42:36

问题


I can't figure out how the firstname and lastname variables are being set in the below C code.

printf("Hello, %s, %s\n", firstname, lastname);

It looks the char [s] parameter of the readln function is setting firstname & lastname.

Is this possible, if so what is this called so I can do a bit of research.

Thanks

Edit: Below is a simpler version. It looks like the parameter is setting a variable.

int foo(char s[]){
    s[0]='w';
    s[1]='\0';

    return 5;
}

int main() {

    char name[2];
    int wtf;

    wtf = foo(name);
    printf("%s\n", name);
}

Parameter char s[] is setting name


#include <stdio.h>

#define STRLEN 5


int readln(char s[], int maxlen) {
    char ch;
    int i;
    int chars_remain;
    i = 0;
    chars_remain = 1;
    while (chars_remain) {
        ch = getchar();
        if ((ch == '\n') || (ch == EOF) ) {
            chars_remain = 0;
        } else if (i < maxlen - 1) {
            s[i] = ch;
            i++;
        }
    }
    s[i] = '\0';
    return i;
} 

int main(int argc, char **argv) {
    char firstname[STRLEN];
    char lastname[STRLEN];
    int len_firstname;
    int len_lastname;
    printf("Enter your first name:");
    len_firstname = readln(firstname, STRLEN);
    printf("Enter your last name:");
    len_lastname = readln(lastname, STRLEN);
    printf("Hello, %s, %s\n", firstname, lastname);
    printf("Length of firstname = %d, lastname = %d", len_firstname, len_lastname);
}

回答1:


When you pass an array as an argument to a function, it's exactly like passing the array address. Then, the function can modify the context of this address, means the array itself.

E.g the function can be defined as int readln(char *s, int maxlen) and the functionality will stay the same.

When calling the function you could use either readln(firstname, STRLEN) or readln(&firstname[0], STRLEN). Both will work with either of the function definitions (they're orthogonal).

A nice tutorial about this subject.




回答2:


The general term is "pass by reference" - the formal parameter s in readln refers to the same chunk of memory that the actual parameters firstname and lastname do in the respective function calls.

C actually passes all function arguments by value - the formal parameter in the function definition is a separate object in memory from the actual parameter in the function call, and the value of the actual parameter is copied to the formal parameter:

void swap( int a, int b ) // a receives a *copy* of x's value, b receives
{                         // a *copy* of y's value
  int t = a;              // updates to a and b have no effect on x and y
  a = b;
  b = t;
}

void bar( void )
{
   int x = 1, y = 2;
   swap( x, y );          // x and y are not actually updated
}

We fake pass by reference semantics by passing a pointer to the object we want modified:

void swap( int *a, int *b ) // a receives the *address* of x, b receives the
{                           // address of y
  int t = *a;               // updates to *a and *b *do* have and effect on
  *a = *b;                  // x and y
  *b = t;
}

void bar( void )
{
  int x = 1, y = 2;
  swap( &x, &y );          // instead of passing the *values* of x and y,
}                          // we pass their addresses.

Again, a and b are separate objects in memory from x and y, but instead of receiving the values of x and y, they receive their addresses. IOW

 a == &x;
 b == &y;
*a ==  x;
*b ==  y;

The situation gets a little weird with arrays - unless it's the operand of the sizeof or unary & operators (or a string literal used to initialize a character array in a declaration), an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element in the array.

So, if you pass an array expression to a function, what the function actually receives is a pointer to the first element of the array, so you don't need to use the & operator in the function call. That's what's happening in readln; the parameter s points to the first element of the array in the function call.



来源:https://stackoverflow.com/questions/43901087/can-c-function-parameters-set-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!