Using %s to printf
something generally requires a \0
character at the end, which you did not leave room for in your string -- it needs to hold 33 characters if you want 32 "real" characters and a null terminator.
Joining 8 strings to form 1 string in C
Question
I am doing a C
programming school project. In one part of the project, I need to join every 8 strings (each 4 characters in length) to form 1 string (each 32 characters in length).
For example, char *holdBinary[16]
holds 16 strings such as:
holdBinary[0] = "0000";
holdBinary[1] = "0000";
holdBinary[2] = "0000";
holdBinary[3] = "0000";
holdBinary[4] = "0000";
holdBinary[5] = "0000";
holdBinary[6] = "0000";
holdBinary[7] = "0000";
holdBinary[8] = "0000";
holdBinary[9] = "0000";
holdBinary[10] = "0010";
holdBinary[11] = "1010";
holdBinary[12] = "0000";
holdBinary[13] = "0000";
holdBinary[14] = "0000";
holdBinary[15] = "0000";
I need to join every 8 strings in holdBinary
to form 1 string which is held in holdRange
char array. Thus, the results: holdeRange[0] = "00000000000000000000000000000000"
which is formed by holdBinary[0]
, holdBinary[1]
.... holdBinary[7]
and holdeRange[1] = "00000000001010100000000000000000"
.
Here is the code:
char holdRange[2][33]; // I changed here and it works correct now
int hold = 0;
int z = 0;
int index2 = -1;
while(z<16)
{
if(z%8 == 0)
{
index2++;
strcpy(holdRange[index2] , holdBinary[z]);
}
else
{
strcat(holdRange[index2] , holdBinary[z]);
}
z++;
}
printf("%s" , holdRange[0]); --> prints 0000000000000000000000000000000000000000001010100000000000000000
printf("\n");
printf("%s" , holdRange[1]); --> prints 00000000001010100000000000000000
Thus, holdRange[0]
is not equal to what must be. How can I fix it?
Solution
OTHER TIPS
You allocate one block of memory for two strings. I assume that's because you confused yourself with the odd types you use. All you need is char* holdRange[2]
and memory for each of the strings.
Sure, it could be made to work your way, but you're not thinking of \0
either.
If you just want to print out 32 characters and wants the characters stored in contiguous memory, give a format specifier to printf()
:
printf("%.32s" , holdRange[0]);
printf("\n");
printf("%.32s" , holdRange[1]);