c - 不使用 strtok() 的字符串分词器

标签 c pointers tokenize

我正在编写一个不使用 strtok() 的字符串分词器。这主要是为了自己的提高,以及对指针的更深入的理解。我想我几乎成功了,但我一直收到以下错误:

myToc.c:25 warning: assignment makes integer from pointer without a cast
myToc.c:35 (same as above)
myToc.c:44 error: invalid type argument of 'unary *' (have 'int')

我正在做的是遍历发送到该方法的字符串,找到每个分隔符,并将其替换为“\0”。 “ptr”数组应该有指向分隔子字符串的指针。这是我目前所拥有的。

#include <string.h>

void myToc(char * str){
   int spcCount = 0;
   int ptrIndex = 0;

   int n = strlen(str);

   for(int i = 0; i < n; i++){
      if(i != 0 && str[i] == ' ' && str[i-1] != ' '){
         spcCount++;
      }
   }

   //Pointer array; +1 for \0 character, +1 for one word more than number of spaces
   int *ptr = (int *) calloc(spcCount+2, sizeof(char));
   ptr[spcCount+1] = '\0';
   //Used to differentiate separating spaces from unnecessary ones
   char temp;

   for(int j = 0; j < n; j++){
      if(j == 0){
         /*Line 25*/ ptr[ptrIndex] = &str[j];
         temp = str[j];
         ptrIndex++;
      }
      else{
         if(str[j] == ' '){
            temp = str[j];
            str[j] = '\0';
         }
         else if(str[j] != ' ' && str[j] != '\0' && temp == ' '){
            /*Line 35*/ ptr[ptrIndex] = &str[j];
            temp = str[j];
            ptrIndex++;
         }
      }
   }

   int k = 0;
   while(ptr[k] != '\0'){
      /*Line 44*/ printf("%s \n", *ptr[k]);
      k++;
   }
}

我可以看到错误发生的位置,但我不确定如何更正它们。我应该怎么办?我是否正确分配了内存,或者这只是我如何指定地址的问题?

最佳答案

你的指针数组是错误的。看起来你想要:

char **ptr =  calloc(spcCount+2, sizeof(char*));

此外,如果我正确阅读了您的代码,则不需要空字节,因为该数组不是字符串。

此外,您还需要修复:

while(ptr[k] != '\0'){
  /*Line 44*/ printf("%s \n", *ptr[k]);
  k++;
}

不需要取消引用,如果您删除空指针,这应该可以工作:

for ( k = 0; k < ptrIndex; k++ ){
  /*Line 44*/ printf("%s \n", ptr[k]);
}

关于c - 不使用 strtok() 的字符串分词器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25752442/

相关文章:

c - 接受为第二个、第三个等客户端返回 0

c++ - : int (*b)[100]是什么意思

c - 在 C 中的结构中调整数组的大小

c++ - 字符转换解释了吗?

php - 标记字符串并了解分隔符的哪一部分

java - 将多个定界符传递给 StringTokenizer 构造函数

java - 让 stringTokenizer 将一行文本拆分为预定义变量的最佳方法是什么

c - 数独求解 - 在回溯中跳过舞台

c - 确定给定用户内存大小和偏移量的所有可能的 32KB block 数

c - 马尔可夫链测试与实现