C 把长的绳子剪成短的
这段代码应该将长字符串切割成短字符串,但它在gcc中提供了转储的核心。它不会在虚空中退出 在我看来,strtok的工作方式不正确。这是错误的:C 把长的绳子剪成短的,c,string,C,String,这段代码应该将长字符串切割成短字符串,但它在gcc中提供了转储的核心。它不会在虚空中退出 在我看来,strtok的工作方式不正确。这是错误的: #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)
#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;
}
因为字符串文字是两个字符!它既是一个空格,也是一个空终止符,位于C中每个字符串的末尾。但您明确表示它应该是一个1个字符的数组。请正确格式化您的代码。对我来说,步骤1将把所有这些单字符变量名重命名为有用的名称。当然,第2步是使用调试器。第3步,将所有讨厌的指针解引用更改为简单易读的数组表示法,例如。**c+j+t='';->c[j][t]='';。第4步,去掉多余的内容,比如malloc结果的强制转换,然后乘以sizeofchar.fscanffin,%[\n],g;->fscanffin,%*[\n];把它改成2,但没用
char r[1]=" ";