读书人

链表有关问题

发布时间: 2012-02-23 22:01:36 作者: rapoo

链表问题求助

C/C++ code
#include "stdafx.h"#include <stdio.h>#include <stdlib.h>typedef struct asnake{    int x;    int y;    struct asnake * next;}snake;snake * Create(unsigned int n){       snake * phead = NULL;        snake * pone = NULL;       snake * pprevone = NULL;       pone = (snake *)malloc(sizeof(snake));       pone->next = NULL;       pprevone=phead=pone;       for(int i = 0;i<n;i++)       {           pprevone = pone;           pone = (snake *)malloc(sizeof(snake));           pprevone->next = pone;       }       return phead;}snake * getxy(snake *s,int *x,int *y){    x = &(*s).x;    y = &(*s).y;    return s->next;}snake * setxy(snake *s,int x,int y){    s->x = x;    s->y = y;    return s->next;}int main(){    int x,y;    snake * pSHead = Create(5);    snake * pS = pSHead;    while(pS)    {        pS = setxy(pS,30,30);    }    pS = pSHead;    while(pS)    {        pS = getxy(pS,&x,&y);        printf("%d %d \n",x,y);    }    system("pause");    return 0;}

在VS2010调试下
C/C++ code
snake * setxy(snake *s,int x,int y){    /*这里出错*/        s->x = x;    s->y = y;    return s->next;}

test.exe 中的 0x00a31524 处有未经处理的异常: 0xC0000005: 写入位置 0xcdcdcdcd 时发生访问冲突

在DEV CPP 4.9.9.2下编译输出如下结果:
1971756956 2293576
1971756956 2293576
1971756956 2293576
1971756956 2293576
1971756956 2293576
请按任意键继续...

求教...

不是应该输出30的吗......

[解决办法]
C/C++ code
snake * Create(unsigned int n){    snake * phead = NULL;     snake * pone = NULL;    snake * pprevone = NULL;    pone = (snake *)malloc(sizeof(snake));    pone->next = NULL;    pprevone=phead=pone;    for(int i = 0;i<n;i++)    {        pprevone = pone;        pone = (snake *)malloc(sizeof(snake));        pone->next =NULL;        pprevone->next = pone;    }    return phead;}
[解决办法]
C/C++ code
#include <stdio.h>#include <stdlib.h>typedef struct asnake{    int x;    int y;    struct asnake * next;}snake;snake * Create(unsigned int n){       snake * phead = NULL;        snake * pone = NULL;       snake * pprevone = NULL;       pone = (snake *)malloc(sizeof(snake));       pone->next = NULL;       pprevone=phead=pone;       for(int i = 0;i<n;i++)       {           pprevone = pone;           pone = (snake *)malloc(sizeof(snake));           pprevone->next = pone;       }       return phead;}snake * getxy(snake *s,int *x,int *y){    *x = s->x;    //这里,得到x,y的值,非改变它的地址    *y = s->y;    return s->next;}snake * setxy(snake *s,int x,int y){    s->x = x;    s->y = y;    return s->next;}int main(){    int x,y;    snake * pSHead = Create(5);    snake * pS = pSHead;    while(pS)    {        pS = setxy(pS,30,30);    }    pS = pSHead;    while(pS = getxy(pS,&x,&y)) //当pS为NULL时,不能再输出了        printf("%p %d %d \n",pS, x,y);    system("pause");    return 0;} 

读书人网 >C++

热点推荐