【问题标题】:Copy array into array index C将数组复制到数组索引 C
【发布时间】:2021-12-09 01:39:06
【问题描述】:

我想将一个数组复制到位置索引处的第二个数组中。

我所做的是:

uint8_t* _data = (uint8_t *)malloc(8U*1024);
uint32_t index= 4U;
uint8_t name[] ="TEST";
memcpy(&data[index], name, sizeof(uint32_t));
index+= 4U;

当我使用以下方式打印数据时:

    for (int j =0; j<index; j++)
    {
        printf("%c \n",data[j]);
    }

它是空的。 我想在 data[3] "TEST" 处找到

【问题讨论】:

  • data(或_data?请edit并澄清)的前4个元素包含未确定的值,那么您期望什么输出?
  • 同样使用sizeof(uint32_t)在这里没有多大意义,你应该使用sizeof(name)
  • for (int j =0; j&lt;offset; j++) -> for (int j = offset; j&lt; offset + 4; j++)
  • 如果你想找到你复制的内容,你为什么要从不同的地方阅读?

标签: arrays c memcpy


【解决方案1】:

这就是我要做的,以便您可以在所需的索引处复制名称。这个有效,因为您要复制的字符串的长度是 4,而 sizeof(uint32_t) 是 4。否则,您将需要输入要复制的字节的长度。

memcpy((uint8_t*)&_data[index], &name, sizeof(uint32_t));

【讨论】:

    【解决方案2】:

    您从索引 4 复制了数据,但从索引 0 打印。那你想怎么打印呢?

    可视化这个问题:

    int main() 
    {
      uint8_t* data = malloc(8 * 1024); 
                                        
      size_t index = 4;
      uint8_t name[] = "TEST";
      memcpy(&data[index], name, sizeof(name));     
    
      for (size_t j = 0; j < index + sizeof(name); j++) 
      {                                                  
        printf("data[%zu] = 0x%02hhx (%c)\n", j, data[j], isalpha(data[j]) ? data[j] : ' ');
      }
    }
    

    和输出:

    data[0] = 0x00 ( )
    data[1] = 0x00 ( )
    data[2] = 0x00 ( )
    data[3] = 0x00 ( )
    data[4] = 0x54 (T)
    data[5] = 0x45 (E)
    data[6] = 0x53 (S)
    data[7] = 0x54 (T)
    data[8] = 0x00 ( )
    

    希望能帮助你理解问题。

    此外,对于索引,请使用正确的类型 size_t 而不是 intuint32_t

    【讨论】:

    • 你应该提到data[0]data[3]的内容实际上是不确定的。
    • @Oka 在这种情况下没有区别
    • @Oka 因为它不是 UB。
    • 我认为 UB 是错误的术语,但那些 values are indeterminate.
    • @Oka 如果它们是不确定的,它将如何影响示例?有什么危险?它会让这个程序不起作用吗?还是只是一次不成功的pick尝试(与对UB的错误理解有关)?
    【解决方案3】:

    你需要从你写信的地方读。

    你想要这个:

      uint8_t* data = malloc(8U * 1024);    // remove the (uint8_t*) cast, it's useless
                                            // but it doesn't do any harm
      uint32_t index = 4U;
      uint8_t name[] = "TEST";
      memcpy(&data[index], name, sizeof(name));     // use sizeof(name)
    
      //  index += 4U;                                << delete this line
    
      for (int j = index; j < index + sizeof(name); j++)  // start at j = index 
      {                                                   // and use sizeof(name)
        printf("%c \n", data[j]);
      }
    

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多