Unable to pass the generated values from a for loo

2019-08-04 04:58发布

问题:

As per my earlier asked question , i am trying to pass values generated from the code i.e. hashname(variables which are generated in the forth loop, combination of a-z, a four character string) to a structure member, using this code.

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;
             }

              }
          }
        }
    }

But as per its output, only last value produced by the for loop is being copied in the structure.I am unable to understand why this is happening.Although vcd_xyz when printed print all the values generated by for loop.

Variables is a pointer pointing to a structure Variable and Name,NumVariables and hashname are its members. Structure Variable is a member of structure sss i had declared vcd_xyz as a global variable.

回答1:

So many problems:

  1. You never increase count. Okay, you fixed that.

  2. Maybe you meant sss->Variables[count] instead of sss->Variables[0]

  3. And your condition should be if(count >= sss->NumVariables).

  4. You only break out of the most inner-most for-loop.

  5. You don't check if your calloc fails.