在函数中传递字符串(C语言)

7

我有一个小程序:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define SIZE 30

void inverti (char s);

int main ()
{
        char str[SIZE+1];

        gets(str);

        printf ("Your imput: ");
        puts(str);

        invert(*str);

        printf ("It works!");

        return 0;
}

void invert (char s)
{
    int i;

    for (i = 0; i < SIZE + 1; i++)
    {
        if (isupper(str[i]))
            str[i] = tolower(str[i]);

        else if (islower(str[i]))
            str[i] = toupper(str[i]);
    }

    puts(str);
}

哪里出错了?为什么我不能把str传递给我的函数?

In function ‘main’:|
warning: passing argument 1 of ‘inverti’ makes integer from pointer without a cast [enabled by default]|
note: expected ‘char’ but argument is of type ‘char *’|
In function ‘invert’:|
error: ‘str’ undeclared (first use in this function)|
note: each undeclared identifier is reported only once for each function it appears in|
||=== Build finished: 3 errors, 1 warnings ===|

问题已经被回答,但是为什么你把这个函数叫做invert?它根本就不是这个函数的作用。 - smocking
该函数应该将小写字符与大写字符“反转”...也许是我的英语不好的问题 :) - Lc0rE
1个回答

15

你的代码至少存在三个问题。

首先,也是与你特定问题最相关的问题,你将函数参数声明为单个字符:char。要传递一个C字符串,请将参数声明为char *——指向字符的指针也是用于C字符串的类型:

void invert(char *str)

当你传递参数时,你不需要解引用:

invert(str);

请注意,您在函数原型中拼写错误了函数名称:您在那里称其为inverti。原型中的名称必须与代码后面的函数定义中的名称匹配。

您还需要更改已纠正并重新命名的函数原型中的参数类型:

void invert(char *str);

你的代码还有一个问题:你正在使用SIZE迭代字符串。SIZE是数组的最大大小,但不一定是字符串的大小:如果用户只输入了5个字符怎么办?你应该检查并使用函数strlen获取实际长度,在循环中,只迭代字符串的实际长度。


我需要在“void invert(char *str)”函数中重新声明“str”函数吗?为什么会显示“error: ‘str’ undeclared (first use in this function)”? - Lc0rE
不,它在参数列表中声明。如果您在arg列表中声明它为:_void invert(char *str)_,那么您可以在函数内部使用它。您是否在函数参数列表中将名称更改为_str_?在您的代码中,它只是_s_。 - pb2q
通过您提出的方式修改代码后,Code::Blocks会警告我出现错误:'str'未在此函数中声明(第一次使用)。 - Lc0rE
仔细逐行检查您的代码。您可能会输错某些内容。请确保在函数中,您使用了_str_,包括函数参数列表,在声明为void invert(char *s)时。 - pb2q

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接