2

what is the best solution to copy a char array -which may contains multiple null characters- to another char arrays of arrays?
for example:

char src[11] = "ab\0cde\0\0fg"
char des[2][6];  

at the end

   des[0] should be ---> ab\0cd    +  \0 
   des[1] should be ---> e\0\0fg   +  \0

note: it should be done just in C and not C++

1 Answer 1

4

you are looking for memcpy

memcpy(des[0] // target void *
     , src    // source void *
     , 5      // number of bytes to copy
     );
des[0][5] = '\0';

memcpy(des[1]  // target void *
     , src + 5 // source void *
     , 5       // number of bytes to copy
     );
des[1][5] = '\0';
Sign up to request clarification or add additional context in comments.

5 Comments

And what about null charechter that should be added at the end of each row of des?
@osyan edited, didn't quite grasp that you wanted it that way.
@SergeyL.:should not there be &des[0]?
Now this is some weird coding style... Keeping the function arguments on multiple lines is good for readability and comments, but usually you put the commas after each argument, on the same row.
@Lundin everyone in his own style, I do it this way so that I can comment out any line in order to add/remove arguments. Most compilers don't understand an empty argument as the last one, so I always have the comma before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.