-
Array misbehaving
In my code I initialize an array of 32 ints to 0. From then on, depending on the string passed to the function, appropriate array elements are changed to 1. Here is my code so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void binary_converter (int number,int *s, int n)
{
int *data;
data = (int*) calloc (n, sizeof (int));
int i, remainder;
for (i = 0; i < n; i++){
remainder = number % 2;
number = number / 2;
data[i] = remainder;
}
while (i >= 0){
*(s++) = data[--i];
}
}
void final_convert (char opcode[], int operand[], int binary[], int temp[], int type)
{
int i = 0, j;
int rs, rt, rd, imm;
if ((type == 2) || (type == 3)){
if (strcmp ("addi", opcode) == 0){
binary[2] = 1;
}else if (strcmp ("lw", opcode) == 0){
binary[0] = 1; binary[4] = 1; binary[5] = 1;
}else if (strcmp ("sw", opcode) == 0){
binary[0] = 1; binary[2] = 1; binary[4] = 1; binary[5] = 1;
}
rt = operand[0];
rs = operand[1];
imm = operand[2];
binary_converter (rs, temp, 6);
i = 1;
for (j = 6; j < 11; j++){
binary[j] = temp[i]; i++;
}
binary_converter (rt, temp, 6);
i = 1;
for (j = 11; j < 16; j++){
binary[j] = temp[i]; i++;
}
binary_converter (imm, temp, 17);
i = 1;
for (j = 16; j < 32; j++){
binary[j] = temp[i]; i++;
}
}
}
int main (void)
{
int i;
int operand[0];
char opcode[] = "lw";
int binary[32] = {0};
int temp[17];
operand[0] = 1;
operand[1] = 4;
operand[2] = 6;
final_convert (opcode, operand, binary, temp, 2);
for (i = 0; i < 32; i++){
printf ("%d", binary[i]);
}
printf ("\n");
return 0;
}
The only thing that malfunctions is when I try to change binary[0] to 1 when opcode is either "sw" or "lw". What am I doing wrong and why does it refuse to change binary[0] to 1, which is such a basic thing to do? thanks
-
int operand[0]; - this is array of 0 elements, so it cannot hold any data... all data you have stored in the array are written outside it - overwriting oter data...
try
Code:
int operand[0];
char opcode[] = "lw";
int binary[32] = {0};
int temp[17];
operand[0] = 1;
operand[1] = 4;
operand[2] = 6;
printf("%c%c - %02X%02X",opcode[0],opcode[1],(unsigned int)opcode[0],(unsigned int)opcode[1]);
to see it by yourself...
you are lucky you program does not crash yet...