strsep的用法

一.出现段错误

看下面两种写法

1.

 

#include
#include

struct item
{
    char name[32];
    char *value;
    struct item *next;
};


int main()
{
    char *channel,*start,*end;
    struct item test;

    snprintf(test.name,31,"%s", "channel");
    test.value = (char *)malloc(128);
    snprintf(test.value,127,"%s","1-15,17-31,43,55");
   
    if(!strcasecmp(test.name,"channel"))
    {
        while(channel = strsep(&test.value,","))
        {
            start = strsep(&channel,"-");
            if(channel)
            {
                end = channel;
                printf("include channel start from %s to %s/n",start,end);
            }
            else
                printf("include channel %s/n",start);
        }
    }


    return 0;
}

 

 

2.写法2

 

#include
#include

struct item
{
    char name[32];
    char value[128];
    struct item *next;
};


int main()
{
    char *channel,*start,*end;
    struct item test;

    snprintf(test.name,31,"%s", "channel");
    //test.value = (char *)malloc(128);
    snprintf(test.value,127,"%s","1-15,17-31,43,55");
   
    if(!strcasecmp(test.name,"channel"))
    {
        while(channel = strsep(&test.value,","))
        {
            start = strsep(&channel,"-");
            if(channel)
            {
                end = channel;
                printf("include channel start from %s to %s/n",start,end);
            }
            else
                printf("include channel %s/n",start);
        }
    }


    return 0;
}

 

段错误

 

二.下面的段错误

 

#include
#include

int main(void)
{
   char *p,*str = "asd@123"; //old
 
  

printf("len = %d/n",strlen(str));
printf("str = %c/n",str[4]);
printf("11/n") ;
str[3]='a' ; //err
strcpy(str,"/0") ; //err
printf("len = %d/n",strlen(str));
printf("str = %c/n",str[0]);

return 0;
}

 

三strsep的一个示例

 

#include
#include

int main()
{
    char *ip = "192.168.0.1";
    char *tmp, *p;
    tmp = ip;
   
    tmp = (char *)malloc(100) ;
    strcpy(tmp,ip) ;
    //strncpy(tmp,99,ip)
    while((p = strsep(&tmp, ".")) != NULL)
    {
        printf("%s/n", p);
    }
}

 

 

 

 

 

你可能感兴趣的:(linux_string)