链表问题求助
#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;}
snake * setxy(snake *s,int x,int y){ /*这里出错*/ s->x = x; s->y = y; return s->next;}
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;}
[解决办法]
#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;}