萌新求助关于单链表的问题

由于刚刚才开始学习链表,自己写了一段尾插法的代码,但是最后老是说Run-Time Check Failure #2 - Stack around the variable 'L' was corrupted.用的是c语言

代码如下

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
	int data;
	struct Node* next;
}Node;
 Node *getheadLink(struct Node* L)
{
	L = (struct Node*)malloc(sizeof(struct Node));
	if (L == NULL)
	{
		exit(0);
	}
	L->next = NULL;
	L->data = 0;
	return L;
}
 void getLink(struct Node* L,int a)
{
	 struct Node* p, *r;
	int b,i;
	r = L;
	for (i = 0; i < a; i++)
	{
		p = (struct Node*)malloc(sizeof(struct Node));
		if (p == NULL)
		{
			exit(0);
		}
		scanf_s("%d", &b);
		p->data = b;
		r->next = p;
		r = p;
	}
	r->next = NULL;
}
void printfLink(struct Node* L)
{
	struct Node* q;
	q = L;
	while (L->next != NULL)
	{
	    printf("\n%d\n", L->next->data);
		L = L->next;
	}
	printf("ok!");
}
int main()
{
	struct Node* L;
	int a;
	L=getheadLink(&L);
	scanf_s("%d", &a);
	getLink(&L, a);
	printfLink(&L);
	return 0;
}

 

#include<stdio.h>
#include<stdlib.h>

typedef struct Node
{
    int data;
    struct Node* next;
}Node;


Node* getheadLink(struct Node** L) //注意**
{
    *L = (struct Node*)malloc(sizeof(struct Node));
    if (L == NULL)
    {
        exit(0);
    }
    (*L)->next = NULL;
    (*L)->data = 0;
    return *L;
}

void getLink(struct Node** L, int a) //注意**
{
    struct Node* p, * r;
    int b, i;
    r = *L;
    for (i = 0; i < a; i++)
    {
        p = (struct Node*)malloc(sizeof(struct Node));
        if (p == NULL)
        {
            exit(0);
        }
        scanf_s("%d", &b);
        p->data = b;
        r->next = p;
        r = p;
    }
    r->next = NULL;
}


void printfLink(struct Node** L) //注意**
{
    struct Node* q;
    q = *L;

    while ((*L)->next != NULL)
    {
        printf("\n%d\n", (*L)->next->data);
        *L = (*L)->next;
    }
    printf("ok!");
}

int main()
{
    struct Node* L;
    int a;
    L = getheadLink(&L);

    scanf_s("%d", &a);
    getLink(&L, a);
    printfLink(&L);
}

更改后的代码如上,注意应该使用二级指针。 

这个涉及到参数的值传递(这个相关概念你可以搜一下)。大致意思是你传进函数的参数会进行拷贝,导致你在函数内部更改的变量并不是你传进去的参数。 举个简单的例子:

void test(int a, int b)
{
    a = 3;
    b = 4;
}

void testPtr(int* aPtr, int* bPtr)
{
    *aPtr = 3;
    *bPtr = 4;
}

void allocateSpace(int* aPtr, int* bPtr)
{
    aPtr = new int(1);
    bPtr = new int(1);
}

void allocateSpacePtrPtr(int** aPtrPtr, int** bPtrPtr)
{
    *aPtrPtr = new int(1);
    *bPtrPtr = new int(1);
}

int main()
{
    int a = 1;
    int b = 1;

    //  值传递简单例子 start
    test(a, b);
    cout << a << b << endl; // 输出为a: 1  b: 1

    testPtr(&a, &b);
    cout << a << b << endl; // 输出为a: 3  b: 4
    //  值传递简单例子 end

    // 下面的例子与你的程序类似:
    int* aPtr = nullptr;
    int* bPtr = nullptr;
    allocateSpace(aPtr, bPtr);
    cout << *aPtr << *bPtr << endl;  // !!!! 这行代码会导致运行异常,理由与值传递的第一个例子相同,即aPtr, bPtr并没有开辟空间, 他们的值仍为nullptr。

    allocateSpacePtrPtr(&aPtr, &bPtr);
    cout << *aPtr << *bPtr << endl;  // 输出为*aPtr: 1  *bPtr: 1

}

你将这个例子看明白应该就理解了, 注意看注释哈。