Home > OS >  Copy array into array index C
Copy array into array index C

Time:10-22

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"

CodePudding user response:

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

CodePudding user response:

You have your data copied from index 4 but you print from index 0. So how do you want to have it printed?

To visualize this problem:

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] = 0xhhx (%c)\n", j, data[j], isalpha(data[j]) ? data[j] : ' ');
  }
}

and the output:

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 ( )

I hope it will help you understand the problem.

Also for indexes use the correct type size_t instead of int or uint32_t.

  • Related