先看一段代码
ElemType *p=(ElemType *)malloc(sizeof(ElemType)*LIST_INIT_SIZE);
这段代码的意思是:
①申请大小为LIST_INT_SIZE乘上
②数据类型为ElemType类型的大小的
一段连续空间.
没毛病对吧
有一道作业题目:(题目不重要,忽略)
线性表的查找算法:
完整代码
#include<bits/stdc++.h>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType string
struct SqList
{
ElemType * elem;
int length;
int listsize;
};
bool cmp(ElemType e1,ElemType e2)
{
return e1==e2;
}
void Init(SqList &L)
{
L.elem = new ElemType[LIST_INIT_SIZE];
//L.elem = (ElemType *)malloc(sizeof(ElemType)*LIST_INIT_SIZE);
L.length=0;
L.listsize=LIST_INIT_SIZE;
}
void ListShow(SqList L)
{
for(int i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;
}
bool ListInsert(SqList &L,int i,ElemType e)
{
if(i<1||i>L.length+1)//现在有length-1个数,占了length个单位,从0到length-1
return false;
if(L.length>=L.listsize)
{
ElemType *newbase = (ElemType *)realloc (L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase)
{
return false;
}
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
ElemType *p=L.elem;
if(L.length==0)
{
*p=e;
L.length++;
return true;
}
for(int j=L.length;j!=i-1;j--)
*(p+j)=*(p+j-1);
*(p+i-1)=e;
L.length++;
return true;
}
void ListDelete (SqList &L,int i)
{
ElemType *p;
for(p=&(L.elem[i-1]);p!=&(L.elem[L.length-1]);p++)
*p=*(p+1);
L.length--;
}
int ListLocate(SqList L,ElemType e,bool (*compare)(ElemType ,ElemType))
{
int i=1;
ElemType *p;
p=L.elem;
while(i<=L.length)
{
if((*compare)(*p,e))//如果*p==e,那么return true,条件为true,退出循环
break;
i++,p++;
}
if(i<=L.length)
return i;
else return 0;
}
int main()
{
//freopen("in.txt","r",stdin);
SqList L;
Init(L);
string str="";
while(cin>>str)
{
if(str=="show")
{
ListShow(L);
continue;
}
if(str=="insert")
{
int num;
cin>>num>>str;
ListInsert(L,num,str);
continue;
}
if(str=="search")
{
cin>>str;
cout<<ListLocate(L,str,cmp)<<endl;
continue;
}
if(str=="delete")
{
cin>>str;
int num=ListLocate(L,str,cmp);
ListDelete(L,num);
}
}
return 0;
}
本地运行:没问题
然而交到作业OJ上
.
.
.
.
.
.
然后我就百思不得其解啊,
就开始不断该代码啊,
修修这里改改哪里啊,
但是啊,
怎么改在本地运行都是对的啊,
一交到OJ上就他妈运行错误啊.
改一次就改好长时间啊,
一改就改两天啊
生无可恋
改完交上去就运行错误啊
然后就一点一点一点一点用cout找啊
然后就突然发现啊,注释掉一条神奇代码就不是运行错误了啊
你猜是那条啊
没错就是本文第一条啊!!!
不用 m a l l o c malloc malloc用 n e w new new空间:
L.elem = new ElemType[LIST_INIT_SIZE];
改完之后:
就他妈完全正确啊
你不支持malloc你说一声啊
这么长的代码
改到心态爆炸啊
割一刀
咳咳,
吐槽完了
正常说话:
为了保证文章正确性
我特意写了一个程序检验malloc正确性
#include<bits/stdc++.h>
using namespace std;
#define ElemType int
int main()
{
ElemType *p=(ElemType *)malloc (sizeof(ElemType)*100);
for(int i=0;i<100;i++)
p[i]=i+1;
for(int i=0;i<100;i++)
cout<<p[i]<<" ";
return 0;
}
本地运行没毛病:
交到OJ上:
是输出错误不是运行时错误了
点开看没毛病:
再把int 改为string:
#include<bits/stdc++.h>
using namespace std;
#define ElemType string
int main()
{
ElemType *p=(ElemType *)malloc (sizeof(ElemType)*100);
for(int i=0;i<100;i++)
p[i]="A";
for(int i=0;i<100;i++)
cout<<p[i]<<" ";
return 0;
}
本地运行没毛病:
交上去
至此,就发现了一个很坑的点
拿小本本记下来:
malloc只是分配堆内存(不会调用构造函数), 而new是分配且内存且在此创建一个对象(会调用构造函数)。
所以对于非内部类型的string来说, malloc是不能满足要求的
再割一?
今天好像还是女生节,就顺便祝女神们节日快乐啦