Greetings.
In article <68**************************@posting.google.com >, PX wrote:
Greetings,
Please take a look at following code:
"
struct STR {
char string[32];
... /* something else */
};
int main(int argc, char *argv[])
{
struct STR *ptr;
ptr->string = argv[2];
}
"
The compiler complained "invalid lvalue in assignment" when I tried to
compile. I am wondering why a char pointer can work fine but
ptr-string can't. Is there any fast method that can get this done
instead of writing a for loop to assign characters one by one?
You have two problems here: first, ptr is an uninitialized pointer, which
means that no storage has been allocated for a structure. Even if the
assignment you're trying were allowed, the program would crash or result in
undefined behaviour when run because ptr doesn't actually point to
anything. You need to first use malloc() to create some space for a
structure, or declare some struct STR foo and have ptr point to that with
ptr = &foo.
The second mistake is that ptr->string is an array with fixed storage; you
can't arbitrarily make it point to something else (in this case, argv[2]).
You could either change the type of ptr->string to a character pointer and
leave the assignment as-is, or you could change the assignment to a call to
strcpy(). Exactly which method you choose depends on what the program is
trying to do; in particular, the strcpy() technique will work only if
you're sure argv[2] will never exceed 32 characters in length (including
the terminating null character).
Regards,
Tristan
--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard
(7_\\
http://www.nothingisreal.com/ >< To finish what you