簡體   English   中英

如何使用 malloc、strtok_r 將輸入作為字符串讀取並存儲每個單詞(單詞是由空格分隔的任何內容)到二維數組?

[英]How do I read input as a string and store each word (a word is anything separated by a space) to a 2d array using malloc, strtok_r?

我是 C 的新手,我知道某些對此有幫助的函數,但是我很難將事情拼湊起來。

到目前為止我使用的過程:使用readline獲取輸入,使用strtok_r計算單詞數,單詞的malloced空間,每個單詞中的計數器字符和malloced空間,然后打印數組。

但是,在運行此程序時,出現段錯誤。

while(inStr = readline("# "))
 {
  
   int totalWords = totalWordsInInput(inStr);
   //malloc the rows (array of pointer-total number of words)
   char** theBigArray = (char**) malloc((totalWords+1)*(sizeof(char*)));           //+1 so we can save a null
   for(int i = 0; i <= totalWords; i++)
   {
       theBigArray[i] = NULL;
   }
   //malloc for each word
   char* ptr = inStr;
   char* saveptr;
   for(int i = 0; i < totalWords; i++, ptr = NULL)     //for every word
   {
       int totalChar = strlen((strtok_r(ptr, " ", &saveptr)));
       theBigArray[i] = (char*) malloc((totalChar+1)*(sizeof(char)));
       for(int j = 0; j <= totalChar; j++)
       {
           theBigArray[i][j] = '\0';
       }
   }

   //populate the malloced array
   char* ptr1 = inStr;
   char* buffer1;
   int k = 0;
   for(int i = 0; (i < totalWords) && (buffer1 = strtok_r(ptr1, " ", &ptr1)); i++)
   {
       theBigArray[i] = buffer1;
   }


   //printing the malloced array
   for(int i = 0; i < totalWords; i++)
   {
       printf("%s", theBigArray[i]);
   }
 }
  
 


  int totalWordsInInput(char* inputString)
  {
   int counterWords = 0;
   char* buffer;
   char* ptr = inputString;

   while(buffer = strtok_r(ptr, " ", &ptr))
   {
       counterWords++;
   }

   return counterWords;
   }

您的代碼中存在一些問題:

  • 將 NULL 分配給 bigArray[i]
  • 循環太多,因為可以加入您在不同循環中執行的“指令”
  • 不完整的代碼
  • 沒有提供警告、細節和錯誤來幫助大家回答你
  • 隱式轉換會丟失整數精度:在獲取 strlen(...) 時從 'unsigned long' 到 'int':您至少應該將它轉換為 (int)。
  • 未使用的變量 'k'
  • 您應該首先為 inStr 分配內存,然后再獲取用戶輸入。 此外,在為數組或其他任何東西分配內存之后,您應該檢查它是否被正確分配。

這是工作代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100

int totalWordsInInput(char *);
void getError(char *);

int main(int argc, const char * argv[]) {
    char *text = (char *) malloc(MAX_LEN);
    if (!text) getError("Input text");
    
    printf("\nInsert some words: ");
    fgets(text, MAX_LEN - 1, stdin);
    text[strcspn(text, "\n")] = '\0';
    text = (char *) realloc(text, strlen(text) + 1);
    if (!text) getError("Input text");
    
    int totalWords = totalWordsInInput(text);
    char **bigArray = (char **) malloc(totalWords * sizeof(char *));
    if (!bigArray) getError("big Array");
    
    char *currentWord, *savePtr = NULL;
    int i = 0;
    for (currentWord = strtok_r(text, " ", &savePtr); currentWord != NULL; currentWord = strtok_r(NULL, " ", &savePtr)) {
        int totalChar = (int) strlen(currentWord);
        bigArray[i] = (char *) malloc(totalChar + 1);
        
        if (!bigArray[i]) getError("bigArray[i]");
        strcpy(bigArray[i], currentWord);
        bigArray[i][totalChar + 1] = '\0';
        i++;
    }
    
    printf("\nSingle words:\n");
    for(int i = 0; i < totalWords; i++) printf("%s\n", bigArray[i]);
    printf("\n\n\n");
    return 0;
}

int totalWordsInInput(char *inputString) {
    int counterWords = 0;
    char *text = (char *) malloc(strlen(inputString) + 1);
    if (!text) getError("total Words In Inpu Text");
    strcpy(text, inputString);
    
    char *word, *savePtr = NULL;
    for (word = strtok_r(text, " ", &savePtr); word != NULL; word = strtok_r(NULL, " ", &savePtr)) {
        counterWords++;
    }
    return counterWords;
}

void getError(char *errorMessage) {
    printf("\nError allocating memory for %s...", errorMessage);
    exit(EXIT_FAILURE);
}

個人提示:

  • 我更喜歡使用 fgets(...) 而不是 readline(...)
  • 我使用了 getError(char *) 過程,以便在內存未成功分配時打印錯誤

我希望它至少對你有一點幫助。

最好的問候,丹尼

暫無
暫無

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

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