我正在编写一些练习程序,但在下面的函数 squeez 中遇到了问题。它返回一个整数而不是预期的 char 数组。该代码意味着用户首先输入一个字符串,然后是他希望删除的字符。 squeez 函数接收两者并输出没有给定字符的字符串。
目前我的函数给出警告:
return 从指针生成整数而不进行强制转换[默认启用]
我知道该函数正在返回类型 'int' b/c 它也显示第二个错误:
格式“%s”需要类型为“char *”的参数,但参数 2 的类型为“int”[-Wformat=]
/* Squeeze Function */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char squeez(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c)
{
s[j++] = s[i];
}
printf("%c %d", s[i], c);
}
printf("%s", s);
s[j] = '\0';
return s;
}
int main(void)
{
int i, c;
char str[10];
for (i = 0; (c = getchar()) != '\n'; ++i)
{
str[i] = c;
}
c = getchar();
printf("%s", squeez(str, c));
return EXIT_SUCCESS;
}
如有任何帮助,我们将不胜感激!
最佳答案
您应该将返回类型更改为char *
:
char *squeez(char s[], int c) {
…
return s;
}
...因为s
是一个指针(字符串第一个字符的地址)。
第二个问题是 squeez()
寻找 '\0'
终止符,但您从未在那里写过终止符。第三个问题是您可能会溢出 10 字节缓冲区。 main()
中的循环应该看起来更像
#include <assert.h>
int main(void)
{
int i;
char str[10];
for (i = 0; i < sizeof(str) - 1; i++)
{
if ((str[i] = getchar()) == '\n')
{
break;
}
}
assert( (i == sizeof(str) - 1) || (str[i] == '\n') );
str[i] = '\0';
printf("%s", squeez(str, getchar()));
}
关于c - 函数返回 Int 而不是 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27792021/