gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:53:28 25 4
gpt4 key购买 nike

我有这个小程序:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com