In the project I'm currently working on, one of the requirements is to use strncat and strncpy to zero pad a string so that it's length is equal to the word size that we set. For example if word size = 8, but the string only has 4 characters, then zero pad the string, so that its length is equal to 8.
So let's say we have 1011 but word size is 8, then we zero pad it to be 00001011.
This is my code so far for that part of the project:
int size = 8;
char *z = "0";
char *u;
u = malloc(size * sizeof(char) + 1);
int diff = size - (strlen(a)+1);
/*Zero Pad with strncpy and strncat*/
while (diff >= 0){
//size_t len = strlen(z) + strlen(u) + 1;
strncpy(u, z, strlen(a) + 10);
strncat(z, u, size);
printf("%s--check\n", u);
diff--;
}
size_t lenr1 = strlen(a) + strlen(u) + 1;
a = strncat(u, a, lenr1);
printf("%s %s %s\n", a, o, b);
It doesn't work. It compiles and everything, but it just repeats 0, 00, 0, 00. strncpy doesn't seem to copy the string after I strncat it. I can't figure out why, and I don't know what steps to take to figure it out.