Kenny Ho
Kenny Ho

Reputation: 423

Trying to terminate a char array and print afterwards

I'm making a char array binary representations of a number. I want to terminate the end of the string with '\0'. It prints the array find aside from the intended garbage value.

However when I try to terminate the array, specifically the index of the garbage value, it won't print out my string.

int main(void)
{
    char s[8] = {0};
    printing_binary(s, 8, 2);

}

void printing_binary(char *s, int length,  unsigned n){

    for(int i = 0; i < length; i++){
        if(1 & (n >> i)){
            s[i] = '1';
        }
        else{
            s[i] = '0';
        }
    }
    //Trying to terminate my string
    //s[length] = '\0';
    printf(s);
}

This code will print out something like 01000000}.

However if I uncomment out s[length] = '\0', it prints nothing/the program stops executing. I've tried printing out "Hello world" after everything.

Upvotes: 0

Views: 78

Answers (4)

FredK
FredK

Reputation: 4084

Another way is to declare i outside the loop. This can be useful if for some reason your logic breaks out of the loop before reaching length

int i;
for ( i=0; i < length; i++ ) {
   ...
}
s[i] = '\0';

Upvotes: 0

Robert Jacobs
Robert Jacobs

Reputation: 3360

If you don't want to add a null terminator, you just have t modify the printf slightly.

int main(void)
{
    char s[8] = {0};
    printing_binary(s, 8, 2);

}

void printing_binary(char *s, int length,  unsigned n){

    for(int i = 0; i < length; i++){
        if(1 & (n >> i)){
            s[i] = '1';
        }
        else{
            s[i] = '0';
        }
    }
    //Trying to terminate my string
    //s[length] = '\0';
    printf("%.*s", length, s);
}

Upvotes: 0

sabbahillel
sabbahillel

Reputation: 4425

You have an 8 bit length which you fill up with the values. For example the value 2 is 00000010 Since you have filled up your string array, you have no room for the ending character. If you define the array size as length+1, then it will work.

int main(void)
{
    char s[9] = {0}; // Note size is length+1
    printing_binary(s, 8, 2);

}

void printing_binary(char *s, int length,  unsigned n){

    for(int i = 0; i < length; i++){
        if(1 & (n >> i)){
            s[i] = '1';
        }
        else{
            s[i] = '0';
        }
    }
    //Trying to terminate my string
    s[length] = '\0'; // s must be an array of size greater than length
    printf(s);
}

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35154

If you define your result array as char s[8], then you must not write anything at position 8 like in s[length] = 0x0 with length==8, because this exceeds the array length. Try:

char s[9] = {0};
printing_binary(s, (9-1), 2);

Upvotes: 2

Related Questions