我是学习 C 语言的新手,我正在尝试学习带有 char 数组的函数。在这段代码中,我想编写一个使用 char 数组作为参数的函数,并给出另一个 char 数组作为结果。当我运行代码时,输出应该是:Helloooo world!
但是,当我运行代码时,程序崩溃了。我该如何解决这个问题?我使用的变量类型正确吗?
#include <stdio.h>
#include <string.h>
char *write();
int main()
{
char x[10] = "ooo";
printf("%s, world!\n", *write(x));
return 0;
}
char *write(char x[10])
{
char str[10];
strcpy(str, "Hello");
strcat(str,x);
x = str;
return x;
}
最佳答案
您有两个问题:
- str 是 write 函数作用域中的局部变量。因此,您将指针返回到不再存在的东西。
- Str 太短,无法容纳您的数据。您从函数参数中复制“hello”(5 个字符)+ 可能的 10 个字符。
char *write();
int main()
{
char x[10] = "ooo";
char buff[20];
printf("%s, world!\n", write(buff, x, 20));
return 0;
}
char *write(char *buff, char *s2, int maxsize)
{
strcpy(buff, "Hello");
if(strlen(buff) + strlen(s2) < maxsize)
strcat(buff,s2);
else
strcpy(buff,"Error");
return buff;
}
关于在c中创建带有char参数的char函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959035/