C code to generate variable with the combination of a-z and max of 4 char

本小妞迷上赌 提交于 2020-03-06 03:57:30

问题


I am trying to write a code that generate variable using a-z only and maximum of 4 char , that means a total of 26*26*26*26 combinations.So here is what i am doing

#include<stdio.h>
static char vcd_xyz[4];
static char     vcd_xyz1[2];
int main()
{
  int i,j;
  for(i=0;i<26;i++)
  {
    vcd_xyz[1] = 'a'+i;
    printf("%d generated variable is   initial is  = %c \n",i,vcd_xyz[1]);

    for(j=0;j<26;j++)
    {
      vcd_xyz[2] = 'a'+j;
      printf("%d generated variable is  = %c \n",j,vcd_xyz[2]);
      //strcat(vcd_xyz[1],vcd_xyz[2]);
    }
  }

  return 0;
}

So it is generating me something like this

0 generated variable is   initial is  = a 
0 generated variable is  = a 
1 generated variable is  = b 
2 generated variable is  = c 
3 generated variable is  = d 
4 generated variable is  = e 
5 generated variable is  = f 
6 generated variable is  = g 
7 generated variable is  = h 
8 generated variable is  = i 
9 generated variable is  = j 
10 generated variable is  = k 
11 generated variable is  = l 
12 generated variable is  = m 
13 generated variable is  = n 
14 generated variable is  = o 

now what i am trying to do is to concatenate these two characters so that i can get a combination like this, aa, ab, ac, ad......ba, bb, bc,bc....ca,cb......and so on, but when i am using

strcat(vcd_xyz[1],vcd_xyz[2]);

its producing a segmentation fault.I understand that i may be do it in wrong way. can any body tell me where i am doing wrong.


回答1:


The arguments of strcat are supposed to be strings and not characters. Just place the characters next to each other like you do now ant it should work. But start with index 0 (as all C arrays start their indexes on zero).

Also, if you later want to print the array as a string, you need a fifth character in the array, and that is the string terminator character '\0', and that terminator character needs to be placed after the last character in the array.




回答2:


i followed Joachim Pileborg words and got you this:

#include<stdio.h>

static char vcd_xyz[5];
static char     vcd_xyz1[2];

int main()
{
    int i,j;
    vcd_xyz[2] = '\0';

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

        for(j=0;j<26;j++)
        {
           vcd_xyz[1] = 'a'+j;
           printf("%d generated variable is  = %c \n",j,vcd_xyz[1]);
           puts(vcd_xyz);
        }
    }

    return 0;
}


来源:https://stackoverflow.com/questions/19089395/c-code-to-generate-variable-with-the-combination-of-a-z-and-max-of-4-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!