Search code examples
clinuxmemcpymemsetc-strings

memset + whitespace + memcpy


How can i set a character array say of size 100 to whitespace and then copy 10 charters to that same string from other. For example:

there is one char array a[100] To do : set all of it to whitespace

Now there is another array : b[10] (suppose this is filled with some string of length 9) To do : copy this array to the previous one

What iam doing is : memset(a, ' ', sizeof(a));
350         memcpy(a,b, strlen(b))

But iam not getting space that i had set after 10 chars has been copied .


Solution

  • Try the following:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define LENGTH 100
    
    int main(int argc, char *argv[])
    {
        char *a = NULL;
        char b[10] = "abcdefghi"; /* note that this has a trailing null character */
    
        a = malloc(LENGTH + 1);
        if (a) {
            *(a + LENGTH) = '\0';
            memset(a, ' ', LENGTH);
            fprintf(stdout, "a (before):\t[%s]\n", a);
            memcpy(a, b, sizeof(b) - 1); /* strip trailing null */
            fprintf(stdout, "a (after):\t[%s]\n", a);
            free(a);
        }
    
        return EXIT_SUCCESS;
    }
    

    Running this:

    $ gcc -Wall test.c
    $ ./a.out
    a (before):     [...100 spaces...........]
    a (after):      [abcdefghi...91 spaces...]                                                                                           ]