| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Array Problem |
JB> char array[20]="hi";
JB> will compile differently to
JB> char array[20]; strcpy(array,"Hi!");
RS> Yeah, it will, because the first allocates 20 bytes, and sets the
RS> first three bytes to 'h', 'i', and 0, respectively, whereas the
RS> second just allocates 20 bytes, and waits until strcpy() changes
RS> them.
DM> More than that, the first one will allocate 20 bytes, set the first to
DM> 'h', the second to 'i', and the rest to nul. The second one
DM> will leave the entire block of 20 characters alone, and
DM> then proceed to change the first three, without changing
DM> the last seventeen.
Hmm. I knew the latter would leave the rest of the array alone,
since there's no way to know how much memory has been allocated for
the string when strcpy() is called. As for the first, I wasn't
aware that the remainder of the array was padded with NULs. Is
this just how some compilers do it, or is it mandated by the
standard? I can't see any reason for this being necessary, since a
single NUL is enough.
RS> My point wasn't this; it was rather that the NUL is tagged onto the
RS> ends of strings if you initialized them when you declared them.
RS> For example,
DM> This is not entirely true.
DM> char array[2] = "hi";
DM> This you think should take three bytes - but ANSI C allows this
DM> particular construct to take the two you asked for. You're asking for
DM> trouble if you try to use printf, strcpy, or any other
DM> "string"-like function, on it. However, accessing array[0]
DM> and array[1] is perfectly fine.
Hmm, slick. I didn't know that. I s'pose it's handy if you want
to initialize char arrays that aren't to be used as strings, or if
you have fixed-length fields that you'll use in routines like
strncpy() and printf("%2s",array). I learn new things in this echo
all the time. :)
RS> even though there isn't room. You're right, a good compiler may
RS> issue a warning here, but that's about it. If you run this code,
DM> Nope - a good compiler should say nothing.
Hmm. I bet my compiler issues a warning.
... Where do you want Bill Gates to go today?
___ Blue Wave/DOS v2.30 [NR]
--- Maximus 2.01wb
* Origin: Basic'ly Computers: Mooo-ing Right Along. (1:153/9)SEEN-BY: 396/1 632/0 371 633/260 262 267 270 371 634/397 635/506 728 639/252 SEEN-BY: 670/218 @PATH: 153/104 2 716 7715 140/1 396/1 633/260 635/506 728 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.