1

so I am working on my Binary adding program, but now I am stuck. I want to declare 2 variables for the first binary and second one, so I use the getBinary function I created to declare these 2. However, after I entered value for firstBin, I got the value I want, but after I entered the value for secBin, the value of firstBin somehow changes and become the same as secondBin. I was hoping for the variable to be unchangable. Thanks for the help

#include <stdio.h>
int * getBinary(){
        int i;
        int j;
        static int first8bits[8];
        for (i = 0; i != 8; i++){
            printf("Input 8-bits Binary:");
            scanf("%d",&first8bits[i]);
        }
        for (j = 0; j != 8; j++)
            printf("%d",first8bits[j]);
        printf("\n");
        return first8bits;
        }

int main(){
    int o;
    printf("Input the first Set of Binary...");
    const int * firstBin = getBinary();

    printf("Input the second Set of Binary...");
    int * secBin = getBinary();

    for (o = 0; o != 8; o++)
            printf("%d",firstBin[o]);
}
Kako Kong
  • 13
  • 4

1 Answers1

2

Because of the static keyword.

Don't use static. Try:

int* first8bits = malloc(8 * sizeof(int));

This way you will allocate new memory each time you call it. You can still access it with the same [ i ] subscript. Remember to free the memory again at the end of main!

free(firstBin);
free(secBin);
StBlaize
  • 523
  • 3
  • 8
  • 1
    Nit... Instead of telling the person `"Try:"`, tell them "You can accomplish what your are trying to do by:". Why? When telling someone to just "try" something, it sounds if you are unsure if it will work and they should just "try" and find out. You answer is fine, convey you are confident in its correctness. – David C. Rankin Nov 21 '19 at 01:18