memset + whitespace + memcpy
Question
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...] ]
OTHER TIPS
You are missing the null \0
character at the last position of the array.
You'll see. Try the following code:
for (int i = 0; i <= 99; i++)
printf("%c", a[i]);
printf("\n");
The reason is when you memcpy
the string to a
, a NULL character is placed in a[10]
. If you only output a
, the output will stop just before the NULL.
don't you think that you need to type cast to (char *)
a = (char *) malloc(LENGTH + 1);