怎样把一个char数组赋值给另一个char数组?

我的一个数组char1,大小是1024,但里面数据只有“abcdefg”,后面就为空。另一个数组是char2,大小等于“abcdefg”,即为7.我想要把char1复制给char2.该怎么办呢???c++

第1个回答  推荐于2017-09-13

简单的可以使用memcpy,举个例子

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
char a[30];
char b[25]="abcdefgagh";

memcpy(a,b,strlen(b));
//a使用字串形式打印
a[strlen(b)]='\0';
printf("a=%s\n",a);
return 0;
}

第2个回答  2007-05-28
#include <string>
using namspace std;

//char2最好有8个字节,因为末尾要有'\0'
strncpy( char2, char1, 8 );

PS.strcpy()不会自动开辟空间;
第3个回答  2021-08-03
void CCoinDispensorDlg::OnDis3() //Hopper 3 Dispense coins
{
// TODO: Add your control notification handler code here
UpdateData();
unsigned char buf[32];
//request cirher key 3
unsigned char tx7[5] = {0x00, 0x00, 0x01, 0xF2, 0x00};
unsigned char xu3, lie3, hao3;
if((m_Edit6>=3)&&(m_Edit6<=10))
{
if((m_Edit14>=1)&&(m_Edit14<=255))
{
tx7[0]=m_Edit6;
tx7[4]=tx7[0] + tx7[1] + tx7[2] + tx7[3];
tx7[4] = 0xff - tx7[4] + 1;
mySerial.SendData((const char *)&(tx7[0]), 5);
DWORD t7 = ::GetTickCount();
for (;;)
{
if ((t7 + 200) <= ::GetTickCount())
{
// Sleep(500);
mySerial.ReadData((void *)buf, 10);
int cnt = mySerial.ReadData((void *)buf, 32);
if(cnt ==13)
{
if ((buf[5] == 1)&&(buf[6] == 3)&&(buf[7] == m_Edit6))
{
xu3 = buf[9];
lie3 = buf[10];
hao3 = buf[11];
}
}
memset((void *)buf, 0, 32);
break;
}
}
}
}
//dispense coin 3
unsigned char tx8[9] = {0x00, 0x04, 0x01, 0xA7, 0x00, 0x00, 0x00, 0x00, 0x00};
if((m_Edit6>=3)&&(m_Edit6<=10))
{
tx8[0]=m_Edit6;
tx8[4]=xu3;
tx8[5]=lie3;
tx8[6]=hao3;

if((m_Edit14>=1)&&(m_Edit14<=255))
{
tx8[7]=m_Edit14;
for (int i = 0; i < 8; i++)
{
tx8[8] += tx8[i];
}
tx8[13] = 0xff - tx8[13] + 1;
mySerial.SendData((const char *)&(tx8[0]), 9);
DWORD t8 = ::GetTickCount();
for (;;)
{
if ((t8 + 200) <= ::GetTickCount())
{
mySerial.ReadData((void *)buf, 15);
// if ((buf[14] == 1)&&(buf[15] == 1)&&(buf[16] == m_Edit6)&&(buf[18] == m_Edit14))
memset((void *)buf, 0, 32);
break;
}
}
}
}

下面是执行结果,把buf数组里面的第9,10,11元素64,98,22,拿出来放入第二个数组tx8的4、5、6元素位置,执行后缺不是64,98,22,确是cc,cc,cc,为什么?
第4个回答  2007-05-28
直接用strcpy(char2,char1);就可以了,函数自动为char2开辟空间。
第5个回答  推荐于2017-09-05
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(int argc, char * argv[])
{
char b[8] = "abcdefg";
char a[1024];
int i;
strcpy(a,b);
printf("a=%s\n",a);
printf("b=%s\n",b);
}本回答被提问者采纳
相似回答