如何将输入读取为字符串,并使用malloc、strtok\r将每个单词(单词是由空格分隔的任何东西)存储到二维数组中?

如何将输入读取为字符串,并使用malloc、strtok\r将每个单词(单词是由空格分隔的任何东西)存储到二维数组中?,c,malloc,C,Malloc,我是C语言的新手,我知道某些函数可以帮助我实现这一点,但我很难将它们拼凑在一起 到目前为止,我使用的过程是:使用readline获取输入,使用strtok_r计算单词数,单词的malloced空间,每个单词中的计数器字符和malloced空间,然后打印数组 然而,当运行这个时,我得到一个seg故障 while(inStr = readline("# ")) { int totalWords = totalWordsInInput(inStr); //mal

我是C语言的新手,我知道某些函数可以帮助我实现这一点,但我很难将它们拼凑在一起

到目前为止,我使用的过程是:使用readline获取输入,使用strtok_r计算单词数,单词的malloced空间,每个单词中的计数器字符和malloced空间,然后打印数组

然而,当运行这个时,我得到一个seg故障

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;
   }
while(inStr=readline(“#”)
{
int totalWords=TotalWordsInput(仪器);
//malloc行(指针数组总字数)
char**theBigArray=(char**)malloc((totalWords+1)*(sizeof(char*));//+1,这样我们就可以保存空值

对于(int i=0;i,代码中存在一些问题:

  • 将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);
}
#包括
#包括
#包括
#定义最大长度100
int TotalWordsInput(字符*);
void getError(char*);
int main(int argc,const char*argv[]{
char*text=(char*)malloc(MAX_LEN);
如果(!text)getError(“输入文本”);
printf(“\n插入一些单词:”);
fgets(文本,最大长度-1,标准);
text[strcspn(text,“\n”)]='\0';
text=(char*)realloc(text,strlen(text)+1);
如果(!text)getError(“输入文本”);
int totalWords=TotalWordsInput(文本);
char**bigArray=(char**)malloc(totalWords*sizeof(char*);
如果(!bigArray)getError(“大数组”);
char*currentWord,*savePtr=NULL;
int i=0;
对于(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(“\n单字:\n”);
对于(inti=0;i
个人提示:

  • 我更喜欢使用fgets(…)而不是readline(…)
  • 我使用了一个getError(char*)过程,以便在内存分配不成功时打印错误
我希望它至少能帮你一点忙

致以最良好的祝愿,
Denny

欢迎来到Stack Overflow。请尽快阅读该页面,并访问描述和(MCVE)的链接。提供必要的详细信息,包括MCVE、编译器警告和相关错误(如果有),将允许此处的所有人帮助您解答问题。此外,在C中,不需要强制转换malloc的返回值。请参阅:。
sizeof(char)
被定义为
1
,可以从计算中省略。建议对类型大小使用递减指针,例如
char**theBigArray=malloc((toalWords+1)*sizeof*theBigArray)
。如果要提供sentinel
NULL
作为最后一个指针,则只需在指针上使用
+1
。如果要读取单词
char buf[256];而(fscanf(fptr,“%255s”,buf)==1){/*alloc/add word*/}/code>