時,這是一個字符串分割成字符串根據性格特徵陣列功能:錯誤創建分割功能
char** split(char c,char* src)
{
int i=0,size=mystrlen(src);
int num=count(c,src);
int foundAt;
//For example for the string The0red0ruby0read0to0read,there are five occurences of zero
//so if you used substring and split you would have ten values,but except for the first and
//last values,every other value would repeat twice,so remove these from 10...to give you 8/2 non-repeating values
//the formula: 2+(2n-2)/2 ==>2+n-1 ==>count+1
num=num+1;
//no malloc/calloc here,let substring take care of this...
char* res[num];
while(i<num)
{
foundAt=indexof(c,src);
if(foundAt==0)
{
//ignore
src=substring(src,1,size);
}
if(foundAt==-1)
{
break;
}
if(foundAt>=size)
{
//ignore if found at the last charecter or null terminator
break;
}
res[i]=substring(src,0,foundAt);
src=substring(src,foundAt,size);
if(src==NULL)
{
break;
}
i++;
}
return res;
}
這是我嘗試使用功能:
char* look="Look0here0there0seems0to0be0nothing0here";
char**res=split('0',look);
printf("The first value is %s\n",res[0]);//=>Look
printf("The third value is %s\n",res[2]);//=>there
==6221== Invalid read of size 8
==6221== at 0x4016F9: main (inittest.c:424)
==6221== Address 0xfff0003a0 is just below the stack ptr. To suppress, use: --workaround-gcc296-bugs=yes
==6221==
The first value is Look
==6221== Invalid read of size 8
==6221== at 0x401719: main (inittest.c:425)
==6221== Address 0xfff0003b0 is just below the stack ptr. To suppress, use: --workaround-gcc296-bugs=yes
==6221==
The third value is
我的輔助功能:使用Valgrind的運行程序時得到的結果
int mystrlen(char* val)
{
int i=0;
while(val[i]!='\0')
{
i++;
}
return i++;
}
char* substring(char* src,int start,int end)
{
int i,size_src=mystrlen(src);
if(start>size_src|| start<0)
return NULL;
if(end>size_src)
end=size_src;
//['a','b','c','d'] 1,3 ['b','c']
//starts at start and reads up to but not including end,the extra charecter in calloc is to add a '\0' there
int size_res=end-start;
char* res=calloc(size_res+1,sizeof(char));
for(i=0;i<size_res;i++)
{
res[i]=src[start+i];
}
res[i]='\0';
return res;
}
int indexof(char c,char* src)
{
int i=0;
int size=mystrlen(src);
for(i=0;i<size;i++)
{
if(c==src[i])
return i;
}
return -1;
}
char* mystrchr(char c,char* src)
{
int i=0,size=mystrlen(src);
//must include null charecter
for(i=0;i<=size;i++)
{
if(src[i]==c)
{
return src+i;
}
}
return NULL;
}
int count(char c,char* src)
{
int i,size=mystrlen(src);
int num=0;
for(i=0;i<size;i++)
{
if(c==src[i])
{
num++;
}
}
return num;
}
編輯:
我還試圖使用mystrchr直接獲得的指針在這種情況下與焦炭的條件在零被發現打算每次被稱爲串置換SRC。
我添加了calloc,就像你建議的一樣,結果代碼是http://pastebin.com/kDvs3DR1。這個代碼是使用http://www.compileonline.com/compile_c_online.php測試的。我猜我需要免費當我在我的計算機上使用gcc和valgrind.Do來運行這個字符串數組時,我需要釋放每個字符串,然後纔可以釋放數組呢?另外,如何使用空格作爲分隔符? – vamsiampolu
是的,正好 - 首先釋放元素,然後是指針數組。不管你如何編譯/運行程序 - 當程序終止時,所有內存都將被釋放。只需使用''「'代替delim變量... – bbonev