プログラムはファイルから文字列を取得し、その中に文字列「delim」を見つけてそれらを分離する必要があります。動的メモリを使用する必要がありますが、残念ながら完全には使用できません。サイクルの最初の繰り返しの後で、「cpystr」を「SUCCESSZOMBIEAAAAAAAaaaAZOMBIEaaAZOMBIEdf」から NULL に変更する理由は何ですか? それを修正するのを手伝ってください。事前に助けてくれてありがとう!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string>
char** split(const char *str, const char *delim)
{
int cntr1, cntr2, cntr3, cntdelim=0;
bool check;
//counting "delim" in the str
char **maspntr=NULL;
char *cpystr=NULL;
cpystr=_strdup(str); //reserve copy of the "cpy"
strcpy(cpystr,str);
for (cntr1=0;cntr1<(strlen(cpystr)+1);cntr1++) //THE PROBLEM WITH THIS CYCLE!
{
check=1;
for (cntr2=0, cntr3=cntr1;cntr2<strlen(delim); cntr2++, cntr3++) //searching for "delim"
if (!(cpystr[cntr3]==delim[cntr2]))
{
check=0;
break;
}
if (check) //if it's foound, it copies the first N characters as the first element of pointers' array
{
maspntr=(char**)realloc(maspntr,(cntdelim+1)*sizeof(char*));
maspntr[cntdelim]=(char*)calloc(cntr1, sizeof(char));
cntdelim++;
for (cntr3=0;cntr3<=(strlen(cpystr)-(cntr1+strlen(delim)-2));cntr3++)
{
cpystr[cntr3]=cpystr[cntr3+cntr1+strlen(delim)];
cpystr=(char*)realloc(cpystr,(strlen(cpystr)+1-cntr1-strlen(delim))*sizeof(char)); //delete first N characters +"delim" by copying the characters from the end then modifying memory
}
}
if(cpystr[cntr1]='\0') //if it is the end of string return
{
for (cntr1=0; cntr1<sizeof(maspntr); cntr1++)
{
printf(maspntr[cntr1],'\n');
}
free(cpystr);
return(maspntr);
}
} //Changing "cpystr" to NULL right here
}
int main()
{
char singlech;
int len=0;
//copy string from the file to the variable
FILE* foo;
errno_t err;
err=fopen_s(&foo,"input.txt","r");
if( err == 0 )
{
printf( "The file 'input.txt' was opened\n" );
}
else
{
printf( "The file 'input.txt' was not opened\n" );
}
while (!feof(foo)) //rather stupid way of getting memory
{
fscanf_s(foo, "%c", &singlech);
len++;
}
char *str=NULL, *delim=NULL;
str=(char*)calloc(len,sizeof(char));
rewind(foo);
fgets(str,len,foo);
delim=(char*)calloc(sizeof("ZOMBIE")+1, sizeof(char));
strcpy(delim,"ZOMBIE");
split(str,delim);
printf(str);
free(str);
free(delim);
getchar();
}