Home > Blockchain >  Why is my for loop increasing the size of my array in C?
Why is my for loop increasing the size of my array in C?

Time:03-14

I'm trying to make a binary number calculator in c and I'm running into issues of my for loops doubling the size of my second array and adding the first array onto the end. I'm really confused because I thought you couldn't increase the size after already declaring it. It is happening in my equation reading function as well but in this ones complement function it's a bit simpler to see. Any ideas of how to fix this?the codethe output

CodePudding user response:

welcome to stack-overflow. From next time please use inline code editor to put your code instead of images. I have taken effort put your code in the answer itself to explain the problem. Please consider this as courtesy. Its very unusual to do it. But as you are a new member, I'm doing it.

// Cole carson's original code from image:
char * onescomp(char x[16], char y[16]){
    int i;
    for(i=0;i<=15;i  ){
        if(x[i] == '0'){
            y[i] = '1';
            continue;
        }
        else if(x[i] == '1'){
            y[i] = '0';
        continue;
        }
    }
    return y;
}
int main()
{
    char b3n[16]={'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
    char cb3n[16];
    puts(b3n);
    onescomp(b3n,cb3n);
    puts(cb3n);
    return 0;
}

Answer:

  1. You don't need continue; in if-else blocks.
  2. You need to add '\0' in the last cell of cb3n array. so puts() knows when string ends & stop printing.

so to quickly fix this issue you can create array with extra cell and assign all values as '\0'. so after copying fifteen 1's there will be '\0' in the end. I think in your case those extra zeros being printed might be garbage values. It looks like array is doubling but it isn't, its just printing values beyond allocated memory because '\0' has not been provided.

//Quick fix
int main()
{
    char b3n[16]={'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
    char cb3n[17]={'\0'}; // <--- quick fix
    puts(b3n);
    onescomp(b3n,cb3n);
    puts(cb3n);

    return 0;
}
  • Related