Char arrays

D

David Scarlett

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.
 
A

Alex Fraser

David Scarlett said:
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 said:
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
 
E

Emmanuel Delahaye

In 'comp.lang.c' said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top