Apologies if this is a newbie question. I'm experienced in other
languages (Lisp, Java, Python...) but a relative newcomer to C. In
the code below, indexToId works most of the time, but sometimes
returns garbage. 'Data' is a large array that's allocated by outside
code and does not change. A colleague told me the problem is that x
is a copy of a bigdatum in an automatic variable. Because it is a
copy, he said, the pointer x.id will become meaningless as soon as x
goes out of scope.
Now my colleague is certainly right. Changing the first two lines of
indexToId to
char *result = Data[i].id;
makes the function work fine.
My question is, why is he right? Even though x is a copy of Data[i],
the id field in both structs is the same pointer, pointing to the same
location in memory. This pointer is returned by indexToId. Even
after x goes out of scope, won't the pointer still be pointing to the
same place?
struct bigdatum {
char id[200];
/* and other fields... */
};
extern struct bigdatum *Data;
static char *indexToId(int i) {
struct bigdatum x = Data[i];
char *result = x.id;
return (result != NULL ? result : "");
}
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|