指针理解错误——01

    我今天写了一个单链表,其实不难,但是我自己犯了一个常识性的错误,我先上一段代码吧

 #include<iostream>
using namespace std;

struct list1
{
    int data;
    list1 *next;
};

list1 * creat(int t)
{
    list1 *head,*cur;
    cur=head;
    for(int i=0;i<t;i++)
    {
        cur=new list1;
        cur->data=i;
        cur=cur->next;
    }
    cur=NULL;
    return head;
}

int main()
{
    list1 *head=creat(20);
    while(head!=NULL)
    {
        cout<<head->data<<" ";//这个地方会是一个死循环
    }
    cout<<endl;
    return 0;
}

其实我的思路就是开始让cur和head相等,然后cur一路连接下去,其实这样的想法是错误的,因为刚开始这两个都是野指针,但是后来在给cur申请新的空间的时候head和cur已经没有关系了,就相当于给cur重新指定一个一样,但是head还是原来的指针。

如果还不懂那么就看看下面这段代码吧!

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
    int *a;
    printf("%p \n",a);
    a=new int;
    printf("%p \n",a);
    return 0;

}


a指向的地址在申请空间前后指向的地址是完全不一样的

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/80294575
今日推荐