在c中创建带有char参数的char函数

标签 c arrays function char

我是学习 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;
}

最佳答案

您有两个问题:

  1. str 是 write 函数作用域中的局部变量。因此,您将指针返回到不再存在的东西。
  2. 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/

相关文章:

java - 为什么 String[] 给出不同的长度并分割给定的字符串?

function - Go 的 struct 方法在调用中抛出太多参数

C - 如何将 ASCII 代码附加到 char 数组

c - 在此代码中除了使用 gets(c) 和 gets(s) 之外,还有什么替代方案?

arrays - 这个集合/数组操作有名称吗?

c - 从C中读取未知数量的int的txt文件

c - 如何在 C 中删除 linux 上的 root 权限?

c - 如何强制将 SIGILL 发送到我的程序?

javascript - 如何在 Javascript 上创建函数后更改接受的参数?

Javascript 函数不改变输入的问题