c - 在函数中传递字符串 (C)

标签 c string

我有这个小程序:

#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 ===|

最佳答案

您的代码至少有 3 个问题。

首先,与您的具体问题最相关的是,您已将函数的参数声明为单个字符:char。要传递 C 字符串,将参数声明为 char * - 指向字符的类型也用于 C 字符串:

void invert(char *str)

并且在传递参数时不需要取消引用:

invert(str);

另请注意,您在函数原型(prototype)中输入了错误的函数名称:您在那里将其命名为 inverti。原型(prototype)中的名称必须与代码后面的函数定义中的名称相匹配。

您还需要更改更正和重命名的函数原型(prototype)中的参数类型:

void invert(char *str);

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

关于c - 在函数中传递字符串 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11418834/

相关文章:

c - 在同一结构内具有指向自身的指针的结构

c - 指针分配与元素或结构分配有什么区别?

c - 有没有一种方法可以轻松检查字符串是否填充了空格/制表符/EOL 而没有其他内容?

c - 获取带有日期和时间(包括微秒)的时间戳

C:错误端口上的套接字绑定(bind)

string - 如何在VB6中访问字符串的各个字符

c++ - 删除字符串中嵌入的空字符

ruby - 检查字符串是否包含来自特定集合的唯一字符

string - 将多个月份字符串替换为month-ints

python - 在python中以一定间隔从右边拆分一个字符串