Richeek
Richeek

Reputation: 2220

Usage of function putc

I am working on a C program that I did not write and integrating it with my C++ code. This C program has a character array and usage putc function to print the content of it. Like this:

printf("%c\n","01"[b[i]]);

This is a bit array and can have either ASCII 0 or ASCII 1 (NOT ASCII 48 and 49 PLEASE NOTE). This command prints "0" and "1" perfectly. However, I did not understand the use of "01" in the putc command. I can also print the contents like this:

    printf("%d\n",b[i]);

Hence I was just curious. Thanks.

Newbie

Upvotes: 1

Views: 910

Answers (5)

Carl Norum
Carl Norum

Reputation: 224972

The "01" is a string literal, which for all intents and purposes is an array. It's a bit weird-looking... you could write:

char *characters = "01";
printf("%c\n", characters[b[i]]);

or maybe even better:

char *characters = "01";
int bit = b[i];
printf("%c\n", characters[bit]);

And it would be a little easier to understand at first glance.

Upvotes: 4

pmg
pmg

Reputation: 108938

Do the statement you understand.

Simplifying the other one, by replacing b[i] with index, we get

"01"[index]

The string literal ("01") is of type char[3]. Getting its index 0 or 1 (or 2) is ok and returns the character '0' or '1' (or '\0').

Upvotes: 0

Hogan
Hogan

Reputation: 70523

This line is saying take the array of characters "01" and reference an array element. Get that index from the b[i] location.

Thus "01"[0] returns the character 0 and "01"[1] returns the character 1

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70909

The String "01" is getting cast into a character array (which is what strings are in C), and the b[i] specifies either a 0 or a 1, so the "decomposed" view of it would be.

"01"[0]

or

"01"[1]

Which would select the "right" character from the char array "string". Note that this is only possible C due to the definition that a string is a pointer to a character. Thus, the [...] operation becomes a memory offset operation equal to the size of one item of the type of pointer (in this case, one char).

Yes, your printf would be much better, as it requires less knowledge of obscure "c" tricks.

Upvotes: 1

Sniggerfardimungus
Sniggerfardimungus

Reputation: 11831

Nasty way of doing the work, but whoever wrote this was using the contents of b as an array dereference into the string, "01":

"foo"[0] <= 'f'
"bar"[2] <= 'r'
"01"[0] <= '0'
"01"[1] <= '1'

your array, b, contains 0s and 1s, and the author wanted a way to quickly turn those into '0's and '1's. He could, just as easily have done:

'0' + b[i]

But that's another criminal behavior. =]

Upvotes: 1

Related Questions