簡體   English   中英

使用指針數組的拼寫檢查程序

[英]Spell checking program using pointer arrays

我正在嘗試創建一個拼寫檢查程序,該程序讀取一個包含 ~3000 個無序 3-4 個字母單詞的文件,每個單詞都在一行中,將它們按字母順序排序,然后將它們打印出來。

我有一個使用“標准”數組形式 array[][] 的工作版本,但是我試圖修改程序以僅使用指針。 我認為通過根據 char 的大小 * 我的文件的大小分配數組會有足夠的內存讓程序正確執行,但是當我運行我的代碼時,我一直在獲取 SEGV,指向我的 while 循環。

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

void bubbleSortWordsArray(char **array, int wordCount, int arrSize);
void printWordsArray(char **array, int wordCount);
int numOfLines(FILE *filePoint);

int main(int argc, char **argv) {
   FILE *fp = fopen(argv[1], "r");
   int i = 0, size = numOfLines(fp);
   char **words = (char **)malloc(sizeof(char) * size);

   if (fp == NULL) {
      fprintf(stderr, "fopen failed");
      exit(EXIT_FAILURE);
   }
   while (fgets(words[i], size, fp)) {
      words[i][strlen(words[i]) - 1] = '\0';
      i++;
   }
   
   fclose(fp);

   bubbleSortWordsArray(words, i, size);
   printWordsArray(words, i);

   free(words);
   return (0);
}

void bubbleSortWordsArray(char **array, int wordCount, int arrSize)
{
   int c;
   int d;
   char *swap = (char *)malloc(sizeof(char) * arrSize);

   for (c = 0; c < (wordCount - 1); c++) {
      for (d = 0; d < (wordCount - c - 1); d++) {
         if (0 > strcmp(array[d], array[d + 1])) {
            strcpy(swap, array[d]);
            strcpy(array[d], array[d + 1]);
            strcpy(array[d + 1], swap);
         }
      }
   }
}

void printWordsArray(char **array, int wordCount)
{
   int i;

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

int numOfLines(FILE *filePoint) {
  int c, count;
  count = 0;
  for (;; ) {
    c = fgetc(filePoint);
    if (c == EOF)
      break;

    if (c == '\n')
      ++count;
  }
  rewind(filePoint);

  return count+1;
}
char **words = (char **)malloc(sizeof(char) * size);

首先,跳過強制轉換並使用變量而不是類型。 這樣您就可以避免使用char而不是char*創建的錯誤。 在此處閱讀更多相關信息: https : //stackoverflow.com/a/605858/6699433

char **words = malloc(sizeof(*words) * size);

第二。 您在這里所做的只是為一些指針分配空間,但這些指針並不指向任何地方。 之后你需要這樣的東西:

for(int i=0; i<size; i++) 
    words[i] = malloc(sizeof (*words[0]) * maxwordsize);

需要在某處定義maxwordsize地方。 它可能因每個指針而異。

嘗試這樣的事情:

char **words = (char **)malloc(sizeof(char*) * size);
for(i = 0; i < size; i++){
    words[i] = (char*)malloc(sizeof(char) * (someValue + 2));
}

其中someValue將是您單詞的最大長度(如果您只有 3-4 個字母的單詞,則設為 4)。 將 2 添加到此someValue以便您還存儲'\\n''\\0'表示每個單詞的結束。 每個單詞都將是一個新字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM