Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C Moderated > [comp.lang.c.mo...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 2 Topic 893 of 1145
Post > Topic >>

[comp.lang.c.moderated] automatic struct-variable question

by mmcconnell17704@[EMAIL PROTECTED] Feb 13, 2007 at 12:22 PM

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.
 




 2 Posts in Topic:
[comp.lang.c.moderated] automatic struct-variable question
mmcconnell17704@[EMAIL PR  2007-02-13 12:22:33 
Re: automatic struct-variable question
mmcconnell17704@[EMAIL PR  2007-02-16 15:47:21 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Thu Sep 4 23:52:13 CDT 2008.