这段代码有什么问题?

时间:2012-01-31 01:10:33

标签: c

我试图模仿strtok功能,但却出现了分段错误。请帮帮我。

这是我的代码:

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

int main(int argc, char argv[])
{
    int i=0;
    char c[]="get the hell out of here";
    char *p;
    char *temp=(char *)malloc(100);
    while(c[i]!='\0')
    {
        if(c[i]!=' ')
        {
            *temp=c[i];
            temp++;
            i++;
        }
        else
        {
            *temp='\0';
            printf("printing tokenn");
            puts(temp);
            i++;
            temp="";
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:8)

temp="";

这会导致temp指向不可修改的内存,导致下次尝试修改时出现故障。您希望将temp恢复为malloc(您忘记保存)的值。

相关问题