Search code examples
arrayscmemcpy

Copy array into array index C


I want to copy an array into a second array at the position index.

What I did is:

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;

When I print data using:

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

it is empty. I want to find at data[3] "TEST"


Solution

  • You need to read from the same place you were writing to.

    You want this:

      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]);
      }