简体   繁体   English

从主数组中的函数存储令牌(strtok)

[英]Storing token(strtok) from function in array from main

I'm trying to make a function to split a sentence in words and store the words into an array of strings. 我试图做一个函数来将单词拆分成一个单词并将单词存储到字符串数组中。 If I use a global variable it works, the strings are stored nice and the job is done, however, when I try to pass an array defined in main it won't work. 如果我使用全局变量,则可以正常工作,字符串存储得很好,并且工作已完成,但是,当我尝试传递main中定义的数组时,它将无法工作。

void split(char sentence[], char *words[]){
  unsigned char n= 0;
  const char delim n= " ";
  char clone[strlen(sentence)];
  strcpy(clone, sentence);

  char *token;
  token= strtok(clone, delim);

  while(token != NULL){
    words[n++]= token;
    token= strtok(NULL, delim);
  }
  words[n]= NULL; //Needed for future usage of the array;
}

int main(){
  char *sentenceFromMain;
  sentenceFromMain= "A BB CCC DDDD";

  char *wordList[nrOfWords+1]; //I do have another function that counts words

  split(sentenceFromMain, wordList);
  exit(0);
}

If I do in the function, for example, words[0]= "A"; 例如,如果我在函数中执行此操作,则words[0]= "A"; it works. 有用。 Is token return a pointer? 令牌返回指针吗? How should I get only whats stored in it? 我应该如何只存储其中存储的内容? I tried multiple ways to do this, none of them worked well. 我尝试了多种方法来执行此操作,但都没有一个很好的方法。 Every response is welcomed! 欢迎每一个回应!

The problem here is that strtok returns pointers into the string it tokenizes. 这里的问题是strtok将指针返回到它标记化的字符串中。 The pointers you get will be pointers into the clone array, which is local inside the split function. 您获得的指针将是进入clone数组的指针,该数组位于split函数内部。 Once the split function returns the pointers will no longer be valid. split函数返回后,指针将不再有效。

One possible way to solve this problem is to not have a local clone array, but have it externally outside the function, and pass it in as the first argument and use that argument in the call to strtok . 解决此问题的一种可能方法是不具有局部clone数组,而将其外部放在函数外部,然后将其作为第一个参数传递并在对strtok的调用中使用该参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM