【发布时间】:2014-09-08 16:01:46
【问题描述】:
每次代码到达第一个 strtok 时,我都会遇到段错误
token = strtok(commandLine," ");
我只是想解析标准输入并将其存储,使用空格作为分隔符。我看到的很多问题是人们在字符串文字上使用 strtok,我认为这也适用于我的情况,但是我该如何解决呢? 谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
int main(int argc, char* argv[]){
//Used for parsing
char commandLine[255];
char* tokens[10];
char* token;
int counter;
int i;
printf("gets to pt 1\n");
//Parsing
while( fgets(commandLine, 255, stdin) ){
printf("\n%s\n", commandLine);
token = strtok(commandLine," ");
printf("gets here");
counter = 0;
for(counter = 0; token != NULL; counter++){
strcpy(tokens[counter], token);
token = strtok(NULL, " ");
}
}
printf("gets to point2");
for(i = 0; tokens[i] != NULL; i++){
printf("%s ", tokens[i]);
}
编辑:
这是工作代码。
正如 User93353 指出的那样,我必须为我的令牌分配内存,所以我改变了
char* tokens[10]
到
char tokens[10][100]
我的 for 循环没有正确结束,必须更改
tokens[i] != NULL
到
i<counter
-
int main(int argc, char* argv[]){
//Used for parsing
char commandLine[255];
char tokens[10][100];
char* token;
int counter;
int i;
printf("gets to pt 1\n");
//Parsing
while( fgets(commandLine, 255, stdin) ){
printf("\n%s\n", commandLine);
token = strtok(commandLine," ");
printf("gets here");
for(counter = 0; token != NULL; counter++){
strcpy(tokens[counter], token);
token = strtok(NULL, " ");
}
printf("gets to printing");
for(i = 0; i<counter; i++){
printf("%s", tokens[i]);
}
}
}
【问题讨论】:
-
strcpy(tokens[counter], token);:tokens[counter]不指向保留的内存。 -
你必须为你的指针分配内存,即
token = malloc(some_size); -
strlen(tokens[i]) != 0更改为i < counter。因为char tokens[10][100];未初始化。