Search code examples
carraysstringmemcpymemset

Is there any way I can copy values into a specific string position using memcpy()?


I'm struggling to find I way to get the following string using the string.h functions memset(...), memcpy(...) and strcat(...):

0000001234abcd

I'm required to use memcpy and I can not find a way to do so without returning to the begining of the string.

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h>

void main () {
    char string [15];

    memset((void *)string,'0',6*sizeof(char));
    memcpy(string,"1234",4);
    strcat(string,"abcd");

    printf("String: %s\n",string);
} 

Output-> String: 123400abcd

If anyone comes up with an idea, I would appreciate it so much.


Solution

  • You have two main issues:

    • forget to specify offset on use of memcpy
    • not having string null terminated when applying strcat

    Try this:

    char string [15] = {0};
    
    memset(string,'0',6);
    memcpy(string + 6,"1234",4);
    strcat(string,"abcd");
    
    printf("String: %s\n",string);
    

    Output: 0000001234abcd