尝试将字符添加到一个字符阵列 [英] trying to append a character to a character array

查看:118
本文介绍了尝试将字符添加到一个字符阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想字符'T'追加到具有价值的字符数组你好,我确定数组的大小,创建一个新的数组,它是1个字符越大,分配新的字符和 \\ 0'作为最后两个字符。
我不断收到旧值(你好)打印出来。谢谢

 的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;无效追加(字符*字符串,字符CH)
{
  INT大小;
  对于(大小= 0;大小< 255;尺寸++)
  {
    在(string [尺寸] =='\\ 0')
      打破;
  }
  焦温度[尺寸+ 2];
  的strcpy(温度,字符串);
  温度[尺寸+ 1] ='T';
  温度[尺寸+ 2] ='\\ 0';
  的printf(测试字符串是:%S \\ n,温度);
}诠释的main()
{
  CHAR测试[] =你好;
  追加(安培;检验,'T');
  返回0;
}


解决方案

首先,你的函数调用是错误的。它应该是

 追加(测试,'T'); //当一个参数传递给函数,数组衰减到指向它的第一个元素。

然后,你必须删除'\\ 0'从previous串否则你将得到相同的字符串。其因追加字符 CH 后,新的字符串像

 你好\\0吨\\ 0

注意'\\ 0' T 的printf 将停止在那空字符。

您可以覆盖'\\ 0'字符与字符'T'

 温度【尺寸】= CH;
温度[尺寸+ 1] ='\\ 0';


注意:您的程序调用,因为出数组的绑定访问的未定义行为温度在声明

 温度[尺寸+ 2] ='\\ 0';

I'm trying to append the character 't' to a character array having the value of "hello", I'm determining the array size, creating a new array that is 1 character bigger, assigning the new char and '\0' as the final two characters. I keep getting the old value(hello) printed out. thanks

#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;
}

解决方案

First, your function call is wrong. It should be

append(test,'t');  // When an argument to a function, array decay to pointer to its first element.

Then, you have to remove the '\0' from the previous string otherwise you will get the same string. Its because after appending the character ch, the new string will look like

"hello\0t\0"  

Notice the '\0' before t. printf will stop at that null character.

You can overwrite that '\0' character with the character 't' as

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


Note: Your program invokes undefined behavior because of out of bound access of array temp in statement

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

这篇关于尝试将字符添加到一个字符阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆