Reputation: 35
I have the following code in C which is supposed to return a 4-bit binary representation of every number in a 8-digit long string of numbers. For some reason it's looping infinitely now.
The current output looks like this (with 12345677
as input): 0001 0010 0011 0000 0000 0000 0000 0000 0000 ...
(endless zeroes). As you can see the first 3 numbers work (which I think is very odd).
What is going wrong here?
#include<stdio.h>
#include<stdlib.h>
#define LENGTH 8
int main()
{
char number[LENGTH];
printf("Geef nummers in : ");
scanf("%s", number);
printf("Resultaat : ");
for(int i=0; i<LENGTH; i++) {
char re[4];
re[3] = ((number[i]) & 1) ? '1' : '0';
number[i] >>= 1;
re[2] = ((number[i]) & 1) ? '1' : '0';
number[i] >>= 1;
re[1] = ((number[i]) & 1) ? '1' : '0';
number[i] >>= 1;
re[0] = ((number[i]) & 1) ? '1' : '0';
number[i] >>= 1;
re[4] = '\0';
int res = atoi(re);
printf("%04d ", res);
}
printf("\n");
}
Upvotes: 0
Views: 142
Reputation: 20734
You only declare 4 elements for re
(0
through 3
inclusive) but you use a 5th element when doing re[4]
. You are invoking undefined behavior at that point. You need to define re
as:
char re[5];
Upvotes: 3
Reputation: 6116
You are accessing over the bounds of array re
, by assigning value to re[4]
.
As Jim Buck said, use char re[5]
, or use index 3
as the last one for array re
.
Upvotes: 0