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

p指针移动和内存分配有关问题

2013-03-21 
p指针移动和内存分配问题#includemalloc.h#includestdio.h#includestdlib.htypedef struct Lnode{in

p指针移动和内存分配问题


#include<malloc.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct Lnode{   
    int  data;
    struct Lnode *next;
}Lnode;
void list_create(Lnode *L);
void print(Lnode *L);

int main(void)
{
    Lnode L;
printf("%d\n",sizeof(Lnode));
    list_create(&L);
    print(&L);
}
void list_create(Lnode *L)
{
    int i,n;
    Lnode *p;
L->next=NULL;//create list with a head node
    printf("Input the length of the list:\n");
    scanf("%d",&n);//the next node is null
    for(i=1;i<=n;i++){
        p=(Lnode *)malloc(sizeof(Lnode));
printf("Input data%d ",i);
        scanf("%d",&p->data);
        p->next=L->next;//add the next node
        L->next=p;
    }
}//CreateList_l
 
void print(Lnode *L)
{
int i;
    Lnode *p;
    printf("Now the datas int the linked list is\n");
    for(p=L->next;p!=NULL;p=p->next){
++i;
        printf("%d ",p->data);
}
printf("\n%d\n",i);
}

我的问题是:
(1)main函数中sizeof(Lnode)的是8,怎么计算的啊?我机子sizeof(int)是4
(2)list_create()中,我输入n=3,表明申请了3*sizeof(Lnode)的内存空间,在print()中,我用i跟踪了p指针的移动,发现输出i的结果是7,p是从L->next即地一个节点开始移动的,p是移动了7+1=8次吗?p指针是怎么移动的啊?是一个字节一个字节移动吗?
[解决办法]
1.一个int + 一个指针类型 大小为8
2.i没有赋初始值,结果是未定义的。
[解决办法]
(1)你用的是Lnode类型,中间有一个4字节的int,一个4字节的Lnode型指针,所以是4+4=8字节
(2)你的程序是错的,在void print(Lnode *L)函数中要初始化i
如代码

void print(Lnode *L)
{
int i=0;
    Lnode *p;
    printf("Now the datas int the linked list is\n");
    for(p=L->next;p!=NULL;p=p->next){
++i;
        printf("%d ",p->data);
}
printf("\n%d\n",i);
}


你使用的是单链表的头插法,具体什么的你去搜一下 “链表头插法” 就什么都知道了, 好好学习数据结构。
[解决办法]
我日,楼上 撞衫了
[解决办法]
引用:
我日,楼上 撞衫了

wo ca le!

[解决办法]
google 指针步长
[解决办法]
引用:
引用:我日,楼上 撞衫了
追加一个问题,它的结果是逆向输出的,怎么让它顺向输出啊?想了好久。书上的也是逆向的

刚说你的这个算法是 头插法,而你的输出就是按照链表从头到尾输出,所以输出与你的输入反序。
你可以使用尾插法,就可以输出正序了,如代码

void list_create(Lnode *L)


{
    int i,n;
    Lnode *p;
    Lnode *q;
    q = L;
    L->next=NULL;//create list with a head node
    printf("Input the length of the list:\n");
    scanf("%d",&n);//the next node is null
    for(i=1;i<=n;i++){
        p=(Lnode *)malloc(sizeof(Lnode));
        printf("Input data%d ",i);
        scanf("%d",&p->data);
        //尾插法
p->next=NULL;
        q->next=p;
        q=p;

    }
}//CreateList_l

热点排行
Bad Request.