C函数参数可以设置变量吗? [英] Can C function parameters set variables?

查看:96
本文介绍了C函数参数可以设置变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在下面的C代码中设置名字和姓氏变量.

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);

看起来readln函数的char [s]参数正在设置名字&姓.

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.

谢谢

下面是一个简单的版本.看来该参数正在设置变量.

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);
}

char s []参数是设置名称

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);
}

推荐答案

将数组作为参数传递给函数时,就像传递数组地址一样.然后,该函数可以修改该地址的上下文,即数组本身.

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.

例如,该功能可以定义为int readln(char *s, int maxlen),并且功能将保持不变.

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

调用函数时,可以使用readln(firstname, STRLEN)readln(&firstname[0], STRLEN).两者都可以使用任何一个函数定义(它们是正交的).

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).

关于此主题的不错的教程.

这篇关于C函数参数可以设置变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆