首页 > 代码库 > 随机数生成(主要练习数组指针的使用)

随机数生成(主要练习数组指针的使用)

Public char *random_num()
{
    int *a,n=8,i,j;
    char *p = (char *)malloc(sizeof(char)*9);
    memset(p,0,sizeof(p));
    a = (int *)calloc(n,sizeof(int));
    for (i=0;i<n;i++)
    {
loop:
        a[i] = rand()%10;
        for(j=0;j<i;j++)
            if (a[i] == a[j]) goto loop;
    }
    sprintf(p,"%d%d%d%d%d%d%d%d",a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);
    return p;
}

Public char * str_digit(int n)
{
  int i;
  char *sran = NULL;
  char (*p)[9];
  p = (char (*)[9])malloc(sizeof(char)*n*9);

  srand(time(NULL));
  for(i=0;i<n;i++)
  {
   sran = random_num();
   memcpy(p[i],sran,9);
  }
  sran = NULL;

  return (char *)p;
}

Public char * digit(int n)
{
 char (*s)[9] = NULL;
 s = (char (*)[9])str_digit(n);
 char *result = NULL;
 result = (char *)malloc(sizeof(char)*100);
 memset(result,0,sizeof(result));
 int i;
 for (i=0;i<n;i++)
 {
   sprintf(result+i*9,"%s ",s[i]);
 }
 result[strlen(result)-1] = \0;
 return result;
}

 

随机数生成(主要练习数组指针的使用)