0

这是一个家庭作业问题。该程序构建成功,但无法运行。它刚刚停止。我试图使用“结构”来制作一个列表。我不知道我的“插入”函数有什么问题。这是我第一次来这里,希望我能得到一些建议。

//============================================================================
// Name        : test2.cpp
// Author      : yan zeng
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int BOOLEAN;
using namespace std;

struct Node {
    int value;
    struct Node *next;
};

void insert(int x, struct Node **pL);

void insert(int x, struct Node **pL){

    if (*pL == NULL) {
        struct Node **pL = (struct Node **) malloc(10 * sizeof(int *));

        (**pL).value = x;
        (*pL)->next = NULL;

    }

    else
        insert(x, &((*pL)->next));

}



int main (int argc, char **argv)
{

    // insert code here...

    //    make a list by declaring a pointer to a node

    struct Node *NodePointer = NULL;



    for (int i=3; i<20; i+=2) {
        insert(i,&NodePointer);
    }



}
4

2 回答 2

0

There is quite a few issues in this code, the use of a debugger will definitely help here.

Your program "just stops" because it crashes at

(**pL).value = x;

I am not sure if this code was provided to you as homework to fix, or if the empty function was provided to you, and you need to fill it out. Either way, that line is wrong.

Also, as others mentioned, you are using malloc in a C++ program when you should be using new.

于 2012-04-15T19:17:02.430 回答
0

我能给你的最好建议是学习如何使用调试器。其他建议:不要malloc/free在 C++ 中使用,使用new/delete.

于 2012-04-15T18:44:06.047 回答