如何为2D数组分配随机字符串

问题描述 投票:0回答:1

程序读取每行包含一个单词的文件。读取随机单词后,将随机单词放入指针并返回指针。在主函数中printf(“%s”,func(“ example.txt”,str))在程序运行时会打印不同的字符串。我想在2d数组(20 * 20)(如表格)中执行此操作,但我无法想象如何这样做。当我在内部循环中打印函数时,它在每个循环步骤中都给我相同的词。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char *word(char *file, char *str);

int main() {
     char *str ;
     int i,j;

     str=(char*)malloc(20);
     srand(time(NULL));
     char *puzzle[20][20];
    for(i = 0;i < 20;i++)
    {
        for(j = 0;j < 20;j++)
        {
           puzzle[i][j]=word("words.txt",str);
        }

    }
        for(i = 0;i < 20;i++)
        {
            for(j = 0;j < 20;j++)
            {
           printf("%s     ",puzzle[i][j]);
            }
            printf("\n");
        }
}


char *word(char *file, char *str) {
  int end, loop, line;


  FILE *fd = fopen(file, "r");
  if (fd == NULL) {
    printf("Failed to open file\n");
    return (NULL);
  }

  srand(time(NULL));
  line = rand() % 100 + 1;

  for (end = loop = 0; loop < line; ++loop) {
    if (0 == fgets(str, 20, fd)) {
      end = 1;
      break;
    }
  }
  if (!end)
    return (char*)str;
  fclose(fd);
   free(str);
}
c arrays string random
1个回答
0
投票

我没有您的words.txt文件,所以我在下面创建了一些随机字符串。

和注释:

  • 由于嵌套循环位于main中,因此您的代码在子函数中打开了文件,并返回w / o关闭该文件;然后返回子目录并一次又一次地重新打开...总是最好一次读取并关闭文件,然后再从子目录返回。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char **word(int countString, int maxChars) {
    int i;
    int j;
    int k;
    // allocate memory for pointers that are pointing to each string
    char **arrStr = malloc(countString * sizeof(char *));

    // srand(time(NULL));

    for (i = 0; i < countString; i++) {
        // create a random string with a length of 'k'
        // say, 5 <= k <= maxChars
        k = (rand() % (maxChars - 5)) + 5 + 1;
        // allocate memory for string
        arrStr[i] = malloc(k * sizeof(char));

        for (j = 0; j < k - 1; j++) {
            *(arrStr[i] + j) = rand() % 26 + 'A';
        }

        *(arrStr[i] + j) = '\0';
    }

    return arrStr;
}

int main() {
    int countString = 10;
    int maxChars = 20;
    char **arrStr = NULL;
    int i;

    arrStr = word(countString, maxChars);

    for (i = 0; i < 10; i++) {
        printf("%s\n", *(arrStr + i));
    }

    // do not forget to free the strings
    // and then the string pointers (array)

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.