首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

malloc的有关问题,死了死了

2012-02-12 
malloc的问题,死了死了typedefstructnode{intdatastructnode*next}NodeNode**pathint*pathLength;path

malloc的问题,死了死了
typedef   struct   node{
int   data;
        struct   node   *next;
      }Node;

Node   **path;
int   *pathLength;

path=(struct   node   **)malloc(N   *   sizeof(struct   node*))


pathLength=(int   *)malloc(N*   sizeof(int))

void   push_path(int   x,int   f)
{
Node   *newNode;

newNode   =   (Node*)malloc(sizeof(Node))

newNode-> data   =   f;
newNode-> next   =   path[x-1];
path[x-1]   =   newNode;

pathLength[x-1]++;
}


int   pop_path   (int   x)
{
Node   *deleteNode   =   NULL;
int   f;
if   (path[x-1]   !=   NULL)
{
deleteNode   =   path[x-1];
f   =   deleteNode-> data;
path[x-1]   =   deleteNode-> next;
free(deleteNode);
deleteNode   =   NULL;

pathLength[x-1]--;

return   f;
}
else
return   0;
}


现在想将path[w]复制给path[w],做法如下,重新给path[u]分配空间,长度是path[w]的长度及pathLength[w],可发现malloc之后,path[u]后面只分配了一个Node啊?后果就是memcpy以后,path[u]和path[w]后面的地址一样了?请问问题到底在哪儿啊?不甚感激~


free(path[u]);
path[u]   =   NULL;

path[u-1]   =   (Node*)malloc(pathLength[w-1]*sizeof(struct   node*))

path[u-1]   =   memcpy(path[u-1],path[w-1],pathLength[w-1]*sizeof(struct   node*))

pathLength[u-1]   =   pathLength[w-1];




[解决办法]
free(path[u]);
path[u] = NULL;

path[u] = (Node**)malloc(pathLength[w]*sizeof(struct node*))

path[u] = memcpy(path[u],path[w],pathLength[w]*sizeof(struct node*))

pathLength[u] = pathLength[w];
[解决办法]
path[u-1] = (Node*)malloc(pathLength[w-1]*sizeof(struct node*))

path[u-1] = memcpy(path[u-1],path[w-1],pathLength[w-1]*sizeof(struct node*))

pathLength[u-1] = pathLength[w-1];

改成对 path[u] 的操作 ~

热点排行