| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | C++ strings and arrays |
RT> k.. the problem is this, i can declare a multiple string
RT> array like this..
RT> char names[3][4] = {"BLAH","POOP","CATS"};
RT> name[2]="Paul";
RT> i want the last name to be paul.. but when i use this i
RT> get a "LVALUE REQUIRED" message..
You need to understand that simple assingment is not allowed
with strings in C. You will have to copy the data into the
string array byte by byte. Fortunately, there is a function
designed for this in the standard library.
#include
#include
int main(void)
{
char names[3][5];
strcpy(names[0], "Paul");
puts(names[0]);
}
Notice that the string space includes an extra byte for the
nul terminator. A C string requires a zero byte to let the
standard libraries know where the string ends.
You may use simple assignment with structs of strings.
typedef struct { char S[5]; } MySTR;
#include
int main(void)
{
MySTR names[3];
int name;
names[0] = *(MySTR*)"Paul"; /* Strings are pointers so */
names[1] = *(MySTR*)"Anne"; /* cast to MySTR pointer & */
names[2] = *(MySTR*)"Greg"; /* then dereference to use */
for(name = 0; name < 3; name++)
puts(names[name].S);
return 0;
}
I have never seen this method in use, however, outside of
simple examples such as this. It might be useful, though,
where standard length strings were required.
A more usual approach is to use string pointers without any
stack space allocated to them. Strings on the stack are only
LVALUEs upon initialization, and thereafter must be filled
by byte copying from the source string. If given as pointers,
however, one may reassign them at will. This requires that
the string space to which they point is stable, and will not
be tampered with by your code unintentionally.
#include
int main(void)
{
char buf[16], *names[3];
names[0] = "Paul";
puts(names[0]);
printf("Input names[1] => ");
fgets(buf, 16, stdin);
names[1] = buf;
puts(names[1]);
return 0;
}
> ] * Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)SEEN-BY: 396/1 622/419 632/0 371 633/260 267 270 371 634/397 635/506 728 810 SEEN-BY: 639/252 670/213 218 @PATH: 154/750 222 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™.