c - 尝试将字符附加到字符数组

标签 c arrays string

我正在尝试将字符 't' 附加到值为“hello”的字符数组,我正在确定数组大小,创建一个大 1 个字符的新数组,分配新的字符和 '\0' 作为最后两个字符。 我一直在打印旧值(你好)。谢谢

#include <string.h>
#include <stdio.h>

void append(char * string,char ch)
{
  int size;
  for (size=0;size<255;size++)
  {
    if (string[size]=='\0')
      break;
  }
  char temp[size+2];
  strcpy(temp,string);
  temp[size+1]='t';
  temp[size+2]='\0';
  printf("the test string is: %s\n",temp);
}

int main()
{
  char test[]="hello";
  append(&test,'t');
  return 0;
}

最佳答案

一个有效的函数可以如下所示

void append( const char *string, char ch )
{
    size_t size = 0;

    while ( string[size] ) ++size;

    char temp[size+2];

    strcpy( temp, string );

    temp[size++] = ch;
    temp[size++] ='\0';

    printf( "the test string is: %s\n", temp );
}

而且必须这样称呼

append( test, 't' );

关于c - 尝试将字符附加到字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214287/

相关文章:

java - 基于搜索字符串插入文本的字符串正则表达式

c++ - Makefile 中的多个跃点

基于指向 const 的指针的 C 函数

c - C中的结构和函数作用域有什么区别?

c - C语言用二进制文件保存和读取结构体数组

c - 如何检测C二维数组的溢出?

javascript - 使用 JavaScript 计算输入元素中值的总和

Java对重复值的数组进行排序

c - 在计算字符数后输入文本和 malloc 可能吗? ( C )

python - 有效地在多个字符串定界符上拆分 python 字符串