By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,985 Members | 1,777 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,985 IT Pros & Developers. It's quick & easy.

Zero pad a string using strncpy and strncat

P: 1
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);
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.
Apr 25 '17 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197
Zero-fill right looks like:

Expand|Select|Wrap|Line Numbers
  1. int size = 8;    //size of string
  2.     char* z  = "0";     //one ASCII zero
  3.     char* str = (char*)malloc(size * sizeof(char) + 1);
  5.     strcpy(str, "123");
  6.     while (strlen(str) < size)
  7.     {
  8.         strcat(str, z);
  10.     }
strcat locates the \0 of the original string and replaces the \0 with its string.

In this example str is 123\0. strcat's string is 0\0.

After strcat, str is 1230\0. After another strcat, str is 12300\0. etc...

All you do is write a loop that repeats the strcat so long as there is room in str. In this example, str can have 7 characters plus 1 for the null.
Apr 26 '17 #2

Post your reply

Sign in to post your reply or Sign up for a free account.