我看到了很多带有数组的strtok示例,但没有指向数组的指针。我随便拿了一个,试着猜测它应该是如何工作的。它不是。为什么这会导致总线错误?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
char *str = malloc(16);
memset(str, ' ', 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( " %sn", token );
token = strtok(NULL, s);
}
return(0);
}
char *str = malloc(16); // you allocate memory
memset(str, ' ', 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");