简体   繁体   中英

Variables confusion

I must read more elements P in a function. Is it better to create pElem every time in a loop?

dataStr *  process(char *start, char *stop, GTree* tree)
{
  while ( (cp != NULL) && ( cp   < nextI))
  {
      //I malloc inside of getPElem function
      pElem * p = getPElem(cp, dateP, s);
      free(p);
  }
}

Or should I better initialize once P-element and reuse it every time?

dataStr *  process(char *start, char *stop, GTree* tree)
{
  pElem * p = malloc(sizeof(p));
  while ( (cp != NULL) && ( cp   < nextI))
  {
      fillPElem(p, cp, dateP, s);

  }
  free(p);
}

If one element would be better, should I malloc it one outside the function (function "process" is called in a loop too):

dataStr *  process(char *start, char *stop, GTree* tree, pElem * p )
{

  while ( (cp != NULL) && ( cp   < nextI))
  {

       fillPElem(p, cp, dateP, s);

  }      
}

Or every time inside the function like in the second example?

If you don't need the pElems to live longer than the enclosing scope, there's no need to dynamically allocate at all:

dataStr *  process(char *start, char *stop, GTree* tree)
{
  pElem p;
  while ( (cp != NULL) && ( cp   < nextI))
  {
      fillPElem(&p, cp, dateP, s);

  }
}

(yes, I know that none of cp, nextI etc. are defined - I just copied from the question).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM