首页 > 解决方案 > 使用带有 malloced 指针的 strtok 正确地指向字符串

问题描述

我看到很多带有数组的 strtok 示例,但没有指向数组的指针。我随机拿了一个,并试图猜测它应该如何工作。它没有。为什么这会导致总线错误?

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

int main () {
   char *str = malloc(16);
   memset(str, '\0', 16);
   str = "This - is - foo";

   const char s[2] = "-";
   char *token;
   
   /* get the first token */
   token = strtok(str, s);
   
   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}

标签: cstringpointers

解决方案


   char *str = malloc(16); // you allocate memory
   memset(str, '\0', 16);  // you set it to zero
   str = "This - is - foo";// you loose the reference to it assigning the pointer with the string literal reference
   // now str references string literal
   // as a bonus you got the memory leak as well

你能做什么?:

   char *str = malloc(16);
   strcpy(str, "This - is - foo");

或简单

char str[] = "This - is - foo";

或者

char *str = strdup("This - is - foo");

推荐阅读