Search code examples
cpointersmemorymemcpy

Simple memcpy doesn't seem to work


I am trying to do a simple memcpy as below.

char *token[32];
char *temp_store[4];

for (i = 0 ; i < 4; i++)
{
   memcpy(token[4+i],temp_store[i],strlen(temp_store[i]));
}

I have the following values inside the token array.

temp_store[0] = "5";
temp_store[1] = "6";
temp_store[2] = "7";
temp_store[3] = "8";

I want these 4 values "5" , "6", "7", "8" to be copied to token[4],token[5],token[6] and token[7] respectively.

However I am not getting those values in token[] for some reason.I can't figure out why that is.


Solution

  • I'm not sure what you are trying to do. However, if you're just trying to concatenate a string, memcpy is not the way to go. Use strcat, like so:

    for (i = 0; i < n; i++) {
        strcat(token[i+4], temp_store[i]);
    }
    

    If you are going to do string operations, use null terminated strings and the str* functions. C has support for those, and many of the string operations you'll want (concatenation, length, duplication with allocation, comparison) are in the suite, plus they're less cumbersome to use than mem* functions.