将长弦切成短的东西

时间:2014-05-12 20:01:14

标签: c string

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24

void rez(char **c, char *s, int n, int ks);

void rez(char **c, char *s, int n, int ks)
{
    int t = 0, j = 0;
    char *p;
    p = strtok(s," ");
    t = t + strlen(p);
    if (strlen(p)>N) *(c+j)=(char*)malloc((strlen(p)+1)*sizeof(char));
    else *(c+j)=(char*)malloc((N+1)*sizeof(char));
    while(p!=NULL)
    {
        if (t>N)
        {  
            *(*(c+j)+t) = '\0';
            t = strlen(p) + 1;
            j++; 
            if (t>N) *(c+j)=(char*)malloc(strlen(p)+1);
            else *(c+j)=(char*)malloc(N+1);
        }
        strcat(*(c+j), p);
        c[j][t]=' ';
        p = strtok(NULL, " ");
        t=t+strlen(p)+1;
    }
    c[j][t]='\0';
    for(j=0; j<ks; j++)
    {
        printf("\n  %s", *(c+j));
    }
}

int main(void)
{
    FILE *fin;
    int n, ks;
    char s1[2048], filename[256];
    char **c;

    printf("Enter the file name->");
    scanf("%s", filename);
    fin=fopen(filename,"r");
    if (!fin)
    {
       printf ("Error\n");
       return -1;
    }
    while (fscanf(fin, "%[^\n]", s1)==1)
    {
        fscanf(fin, "%*[ \n]");
        printf("\n String:   %s \n", s1);
        n=strlen(s1);
        ks=n/(N-1)+1;
        c=(char **)malloc(ks*sizeof(char*));
        rez(c, s1, n, ks);
    }
    fclose(fin);
    return 0;
}

这段代码应该将长字符串剪成一些较短的字符串,但它会在gcc中给出“core dumped”。它不会在void rez()中退出。

在我看来,strtok()工作不正常。

1 个答案:

答案 0 :(得分:0)

这是错误的:

char r[1]=" ";

因为字符串文字" "是两个字符!它既是空格又是NULL终结符(位于C中每个字符串的末尾。但是你明确地说它应该只是1个字符的数组。

相关问题