Velocity Reviews > Char arrays

# Char arrays

David Scarlett
Guest
Posts: n/a

 05-15-2004
A couple of questions...

Firstly, can I put an expression inside an array definition?
eg.
char ln[MAX_LINE_LEN+1]; /* MAX_LINE_LEN has been #defined */

Secondly, is the size of a char always 1 byte?

ie. To get a line from stdin, can i do this, assuming the above
definition of 'ln'?
fgets( ln, sizeof(ln), stdin );

Or do I have to do this?
fgets( ln, sizeof(ln)/sizeof(char), stdin );

Thanks.

--
David Scarlett

dscarlett@_ _ _ _ _ _ _ _
_ _ _ _ _ optusnet.com.au

Alex Fraser
Guest
Posts: n/a

 05-15-2004
"David Scarlett" <(E-Mail Removed)> wrote in message
news:Xns94EAC11BE9545dscarlett@211.29.133.50...
> A couple of questions...
>
> Firstly, can I put an expression inside an array definition?
> eg.
> char ln[MAX_LINE_LEN+1]; /* MAX_LINE_LEN has been #defined */

Yes, that's fine.

> Secondly, is the size of a char always 1 byte?

Yes, sizeof(char) is defined to be 1 byte, but 1 byte may have more than 8
bits. See CHAR_BIT in <limits.h>.

> ie. To get a line from stdin, can i do this, assuming the above
> definition of 'ln'?
> fgets( ln, sizeof(ln), stdin );

Yes. The brackets are superfluous when sizeof is applied to an object (as
opposed to a type).

> Or do I have to do this?
> fgets( ln, sizeof(ln)/sizeof(char), stdin );

Since sizeof(char) is 1, this is equivalent to the above. I prefer to avoid
using sizeof on types where possible:

type array[SIZE];
size_t elements = sizeof array / sizeof *array; /* correct for any type */

Alex

Emmanuel Delahaye
Guest
Posts: n/a

 05-15-2004
In 'comp.lang.c', David Scarlett <(E-Mail Removed)> wrote:

> Firstly, can I put an expression inside an array definition?
> eg.
> char ln[MAX_LINE_LEN+1]; /* MAX_LINE_LEN has been #defined */

This is a constant expression. Yes, you can, as long as the resulting
expression fits into the implementation limits.

> Secondly, is the size of a char always 1 byte?

Yes, by-definition.

> ie. To get a line from stdin, can i do this, assuming the above
> definition of 'ln'?
> fgets( ln, sizeof(ln), stdin );

Assuming 'ln' is an array of char, yes. You also can drop the ().

fgets (ln, sizeof ln, stdin);

is the 'canonic' way.

> Or do I have to do this?
> fgets( ln, sizeof(ln)/sizeof(char), stdin );

You don't.

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/