【问题标题】:Unable to pass the generated values from a for loop to a structure无法将生成的值从 for 循环传递到结构
【发布时间】:2013-10-01 06:38:02
【问题描述】:

根据我的earlier asked question,我正在尝试使用此代码将代码生成的值,即哈希名(在第四个循环中生成的变量,a-z 的组合,四个字符串)传递给结构成员。

vcd_xyz[4]='\0';
count = 0;
for(int i=0;i<26;i++)
    {
        vcd_xyz[0] = 'a'+i;
       // printf("%d generated variable is   initial is  = %c \n",i,vcd_xyz[0]);

        for(int j=0;j<26;j++)
        {
           vcd_xyz[1] = 'a'+j;
          // printf("%d generated variable is  = %c \n",j,vcd_xyz[1]);
         //  puts(vcd_xyz);
          for(int k = 0;k<26;k++)
          {
             vcd_xyz[2] = 'a' + k;
            // puts(vcd_xyz);
             for(int l=0;l<26;l++)
             {
               vcd_xyz[3] = 'a' +l;
               count++;
             sss->Variables[0].hashname = (char*)calloc(strlen((char*)vcd_xyz)+1,sizeof(char));
             strcpy(sss->Variables[0].hashname,(char*)vcd_xyz);
             if(count>(sss->NumVariables))
             {
                break;
             }

              }
          }
        }
    }

但根据其输出,只有 for 循环生成的最后一个值被复制到结构中。我无法理解为什么会发生这种情况。尽管 vcd_xyz 在打印时打印了 for 循环生成的所有值。

Variables 是指向结构 Variable 的指针,NameNumVariableshashname 是其成员。 结构变量是结构sss 的成员 我已将 vcd_xyz 声明为全局变量。

【问题讨论】:

  • 你为什么要使用这个:sss-&gt;Variables[0]。它不应该等于循环运行的次数吗
  • 好吧,可以说NumVariables 持有数字值的次数,for 循环生成的值将传递给结构,该怎么做?意味着我没有任何线索。 ..

标签: c structure concatenation


【解决方案1】:

问题太多了:

  1. 你永远不会增加count 好的,你解决了这个问题。

  2. 也许你的意思是sss-&gt;Variables[count]而不是sss-&gt;Variables[0]

  3. 你的条件应该是if(count &gt;= sss-&gt;NumVariables)

  4. 你只能在最里面的for-loop 中使用break

  5. 你不检查你的calloc是否失败。

【讨论】:

  • #5 不得使用,因为 hashname 最多可以是 4 个字符,并且正在打印一个变量,但无论如何,我会使用它..#4 最里面的循环是产生所有我需要的哈希名..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 2021-04-22
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多