C函数参数可以设置变量吗?

标签 c function parameters

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

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

看起来 readln 函数的 char [s] 参数正在设置名字和姓氏。

这是否可能,如果可能的话,这叫什么,所以我可以做一些研究。

谢谢

编辑:下面是一个更简单的版本。看起来参数正在设置一个变量。

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[]为设置名称


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

最佳答案

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

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

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

一个不错的tutorial关于这个主题。

关于C函数参数可以设置变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43901087/

相关文章:

c - 获取栈的起始地址

c - 功能查询

jquery - polymer ! Ajax中调用函数成功

c - 使用 2 函数进行冒泡排序

Java:构建器模式与逻辑分组对象

python - 请求中的数据和参数有什么区别?

c - 在 C 中提示用户输入整数 2> 和 >9

objective-c - 未初始化的外部 NSString 用法

涉及 ; 的结构数组的编译错误代币

c - sprintf 的 MISRA 兼容替代品?