c - 为什么 strcpy 不能正常工作

标签 c string

我想将字符串数组的每个元素复制到另一个字符串数组,但是当我复制一个字符串时,整个数组都会更改为该字符串。以下是代码集。

这是有问题的代码行:

strcpy(MsgList[i].ga_data, a_Database[i].ga_data);

当我检查内容时 a_Database[i].ga_data,如下

"1240,message 7:War of the worlds"

"1238,message 5:Life of this world"

"1236,message 3:world is not enough"

"1235,message 2:What a world!"

因此,不要在MsgList[i].ga_data中填充相同的内容,结果只是“1235,消息2:多么美好的世界啊!” 4次,这是最后复制的元素。

typedef enum
{
  ACK,
  NACK,
  DELETE
}eMsgStatus_t;

typedef struct _Message
{
  eMsgStatus_t status;
  char *ga_data;
  uint16_t time;
}Message_t;
Message_t MessageList[8]={
  {ACK,"1234,message 1:Hello world",1000},
  {NACK,"1235,message 2:What a world!",1011},
  {NACK,"1236,message 3:world is not enough",1022},
  {ACK,"1237,messsge 4:Cruel world",1033},
  {NACK,"1238,message 5:Life of this world",1044},
  {ACK,"1239,message 6:Around the world in 80 days",1055},
  {NACK,"1240,message 7:War of the worlds",1066},
  {ACK,"1241,message 8:End of World",1077}
}; 

Message_t a_Database[20];
Message_t MsgList[20]= {0};

int main()
{
  for (i = 0; i < idx /* total unread message */; ++i)
  {
      strcpy(MsgList[i].ga_data, a_Database[i].ga_data);
      MsgList[i].ga_data[14] = '\0';
  }
}

uint8_t  GetMessages (Message_t *pg_Message)
{
  char i;uint8_t idx = 0;
   for (i = 0; i < 8 /* total message */; ++i)
  {
    if(NACK == MessageList[i].status)
    {
      pg_Message[idx].status = MessageList[i].status;
      pg_Message[idx].ga_data = MessageList[i].ga_data;
      pg_Message[idx].time = MessageList[i].time;
      idx++;
    }
  }
  return idx;
}

最佳答案

首先,你在这里破坏了内存:

strcpy(MsgList[i].ga_data, a_Database[i].ga_data);

因为我看不到 MsgList[i].ga_data 的分配是在哪里完成的, 我认为不是。

然后在此处通过魔数(Magic Number)“14”制作以 null 结尾的字符串:

 MsgList[i].ga_data[14] = '\0';

也可能导致一些内存损坏。

甚至假设您在某处进行分配,您可以在 MsgList[i].ga_data 中观察到完整字符串,这很奇怪,因为您在 14 处进行了 null 终止,它应该类似于:

1235,message 2                                                            
1236,message 3
1238,message 5 
1240,message 7

关于c - 为什么 strcpy 不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901969/

相关文章:

html - 使用 nokogiri 和 ruby​​ on rails 更改 href 属性

ruby - 从 Ruby 中的字符串中删除电子邮件地址

c++ - 如何将存储在字符串变量中的时间转换为时间格式?

c - 如何轻松添加 gmtime 的小时和分钟

c - 将负数分配给 unsigned int 不会导致任何错误?

c++ - 如何将指针视为多数组?

c# - 从 C# 将数据传入和传出 DLL

c - 退出函数时无法维护保存在二维字符数组中的字符串

python - 如何按空格字符拆分列表中的字符串

在matlab中调用C函数的变量地址