I'm expecting string length to be 4 but when I'm doing strlen()
it's coming to 0. There's no error during compiling.
I am not able to understand the reason behind this.
Here's my code snippet:
#include <stdio.h>
#include <string.h>
int main()
{
int N = 6;
char s[4];
int i = 0;
while(N!=0) {
int rem = N%2;
N = N/2;
//printf("%d\n", rem);
s[i] = rem;
i++;
}
//s[0] = 1;
printf("size = %zu", strlen(s));
return 0;
}
Continuing from my comment, 4
is a tiny buffer, don't skimp on buffer size (even though it would work if all goes perfect). When you iterate, always protect your array bounds in the loop itself. Before you can consider s
a string, you must provide the nul-terminating character after the last character in the string (e.g. '\0'
which is equivalent to plain-old 0
)
Note the bold character above. You are assigning the integer value as a character, that won't work. Convert the integer to an ASCII digit with + '0'
. See ASCII Table & Description
Putting it altogether, you would have:
#include <stdio.h>
#include <string.h>
#define MAXC 64
int main()
{
int i = 0, N = 6;
char s[MAXC]; /* always use a reasonable sized buffer */
while (i < MAXC - 1 && N != 0) { /* protect array bounds */
int rem = N % 2;
N = N/2;
s[i] = rem + '0'; /* convert to ASCII digit */
i++;
}
s[i] = 0; /* nul-terminate s */
printf ("size = %zu (and i = %d)\n", strlen(s), i);
return 0;
}
Example Use/Output
$ ./bin/mod2str
size = 3 (and i = 3)
Let me know if you have further questions.