简体   繁体   English

变量混乱

[英]Variables confusion

I must read more elements P in a function. 我必须在函数中读取更多元素P. Is it better to create pElem every time in a loop? 每次循环创建pElem更好吗?

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? 或者我应该更好地初始化一次P元素并每次重复使用它?

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): 如果一个元素会更好,我应该在函数外面对它进行malloc(函数“process”也在循环中调用):

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: 如果您不需要pElems比封闭范围更长寿,则根本不需要动态分配:

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). (是的,我知道cp,nextI等都没有定义 - 我只是从问题中复制过来)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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