|
我写的一个以空白字符我分隔符的(''之间的不打断)打断字符串的函数.
如图:
buf[0] = 0x8049ab8.已经分配过了.
执行buf = (char**)realloc(buf,num);后.
发现&buf[num-1](也就是&buf[4]) = 0x8049ab8.
难道已经分配过的内存还能再分配吗?
还请高手指教.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define TRAN_ABLE (signed char)('\\')
#define TRAN_NOABLE (signed char)('\\')|(0x80)
void tranable(char* s)
{
if(!s)
return;
int i = 1;
while(s != 0)
{
if(s == TRAN_ABLE && s[i - 1] == TRAN_ABLE)
{
s[i - 1] = TRAN_NOABLE;
strcpy(s+i,s+i+1);
}
i++;
}
}
int blockchar(char* s,char**& buf,int& num)
{
if(!s)
{
buf = 0;
num = 0;
return 0;
}
int len = strlen(s);
for(len--; s[len] == ' ' || s[len] == '\t';len--){};
len++;
tranable(s);
int sta = 0;
while(s[sta] == ' '|| s[sta] == '\t')
{
sta++;
}
num = 0;
buf = (char**)malloc(0);
bool spaceAbleFlag = ((s[sta]=='\'') ? false:true);
int i = (spaceAbleFlag ? -1:0);
do
{
i++;
if((s == ' ' || s == '\0') && spaceAbleFlag )
{
num++;
buf = (char**)realloc(buf,num);
buf[num-1] = (char*)malloc(i - sta + 1);
memcpy(buf[num-1],s+sta,i-sta);
buf[num-1][i-sta] = 0;
for(; s==' '||s=='\t';i++){};
sta = i;
}
if(s =='\'')
{
if(s[i-1] != TRAN_ABLE)
{
strcpy(s+i,s+i+1);
i--;
spaceAbleFlag = !spaceAbleFlag;
}
else
{
strcpy(s+i-1,s+i);
i -= 2;
}
}
}while(s != 0);
return num;
}
#include "mystring.h"
int main()
{
int i;
char a[100] = "shi' 'nian sheng si liang mang";
char** b;
int s;
puts(a);
blockchar(a,b,s);
for(i = 0; i < s;i++)
puts(b);
} |
|