推测是跟内存有关的问题,给str2单独malloc一个空间出来就不会出现这个错误。
这里出错的关键在初始化!指针不初始化很危险,定义了一个指针一定要初始化。野指针乱指的,谁也不知道会发生什么可怕的事情。正确代码见【数据结构】4.1串的基本操作。另外关于初始化的重要性有一篇文章还可以https://www.jianshu.com/p/5cbb007e0e2a
附上源代码
#include <stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
typedef struct String{
char * ch;
int length;
}Str;
int StrAssign( Str & str ,char * ch) ;
int GetStrLength(Str str);
int StrCompare(Str s1,Str s2);
int Concat(Str str1, Str str2, Str &str);
int GetSubString(Str str,int pos, int len, Str &substr);
int ClearString(Str &str);
int main(void)
{
Str str1;
Str str2;
// str2.ch = (char*)malloc(sizeof(char)*2);
char ch1[] = "I love China!";
char ch2[] = "I love U!";
char ch3[] = "IP";
StrAssign(str1, ch1);
StrAssign(str2, ch3);
printf("%s\n",str1.ch);
printf("%s\n",str2.ch);
return 0;
}
int StrAssign( Str & str ,char * ch)
{ //赋值
if(str.ch) //如果str.ch原先有存其他东西,就释放掉原先的东西
{
free(str.ch);
str.ch = NULL;
}
int len = 0;
char * c = ch;
while (*c)
{ //求串长
++len;
++c;
}
if(len == 0) //空串
{
str.ch = NULL;
str.length = 0;
return 1;
}
else
{
str.ch = (char *)malloc(sizeof(char)*(len + 1));
if(str.ch ==NULL)//空间分配失败
return 0;
else
{//写法1
c = ch;
for(int i = 0; i <= len ; ++i,++c)
str.ch[i] = *c;
str.length = len;
return 1;
}
// {//写法2
// i = 0;
// c = ch;
// while(c*)
// {
// str.ch[i] = c*;
// ++c;
// ++i;
// }
// str.[++i] = '\0';
// str.length = i;
// }
}
}
int GetStrLength(Str str)
{
return str.length;
}
int StrCompare(Str str1,Str str2)
{ //串比较
for(int i = 0; i <str1.length && i < str2.length; ++i)
if(str1.ch[i] != str2.ch[i])
return str1.ch[i] - str2.ch[i];
return str1.length - str2.length;
}
int Concat(Str str1, Str str2, Str &str)
{ //串连接
if(str.ch)
{
free(str.ch);
str.ch = NULL;
}
str.ch = (char *)malloc(sizeof(char)*(str1.length + str2.length + 1));
if(!str.ch) //空间分配失败
return 0;
int i = 0,j = 0;
while (i <str1.length)
{
str.ch[i] = str1.ch[i];
++i;
}
while(j < str2.length)
{
str.ch[i + j] = str2.ch[j];
++j;
}
str.ch[j] = '\0';
str.length = str1.length + str2.length;
return 1;
}
int GetSubString(Str str,int pos, int len, Str &substr)
{ //求子串
if(pos < 0 || pos >=str.length || len < 0 || len > str.length - pos)
return 0;
if(substr.ch)
{
free(substr.ch);
substr.ch == NULL;
}
if(len == 0)
{
substr.ch = NULL;
substr.length = 0;
return 1;
}
else
{
substr.ch = (char*)malloc(sizeof(char) * (len + 1));
int i = pos, j = 0;
while(i < pos + len)
{
substr.ch[j] = str.ch[i];
++i;
++j;
}
substr.ch[j] = '\0';
substr.length = len;
return 1;
}
}
int ClearString(Str & str)
{ //清空串
if(str.ch)
{
free(str.ch);
str.ch == NULL;
}
str.length = 0;
return 1;
}