来自数组的C链表

时间:2015-04-02 21:38:02

标签: c arrays list

在函数中,我创建了一个大小为2的数组,它将包含两个PolyTerms。然后,在函数中,我创建了一个List。之后,我想将数组元素作为链表传递给List。

我在if语句后收到错误 head-> next = nodePtr; (访问不良)。

感谢。

我的部分代码:

struct Fraction {
    int num;
    int denom;
};

struct PolyTerm {
    int ex;
    struct Fraction coe;
};
typedef struct PolyTerm PTerm;
typedef struct PolyTerm* PTermPtr;

struct PolyListNode {
    PTermPtr termAddr;
    struct PolyListNode* next;
};
typedef struct PolyListNode PList;
typedef struct PolyListNode* PNodeAddr;
typedef struct PolyListNode* PolyList;

PolyList sortPoly(void);

PolyList sortPoly() {

    int arraySize = 2;
    int i = 0;

    //Array of PTermPtr. Each element holds ex, num and denom.
    //Populating 2 elements for arrayTerm

    PTermPtr arrayTerm;
    arrayTerm = (PTermPtr) malloc(arraySize);
    ((arrayTerm) + 0)->ex = 2;
    ((arrayTerm) + 0)->coe.num = 2;
    ((arrayTerm) + 0)->coe.denom = 2;

    ((arrayTerm) + 1)->ex = 3;
    ((arrayTerm) + 1)->coe.num = 2;
    ((arrayTerm) + 1)->coe.denom = 2;

    PNodeAddr nodePtr; //To create nodes
    PolyList head = 0; //New List
    PNodeAddr current; //To store Address of List Head
    current= head; //Store address of head of list

    while (i < arraySize) {

        nodePtr = (PNodeAddr) malloc(sizeof(PList));
        nodePtr->termAddr = (arrayTerm + i);
        nodePtr->next = 0;

        if (current == 0) {
            head->next = nodePtr; //ERROR. Bad Access
        } else {
            while (current != 0) {
                current = current->next;
            }
            current->next = nodePtr;
        }
        i++; 
    }
    free (arrayTerm);
    return head;
}

1 个答案:

答案 0 :(得分:2)

只要想想代码第一次通过循环时会发生什么:

PolyList head = 0; //New List

Head现在为0(或null)。

current= head; //Store address of head of list

当前和头部现在为0

    if (current == 0) {

是。

        head->next = nodePtr; //ERROR. Bad Access

尝试访问0和null的head。你正在访问null


还应该注意,传递给malloc的大小是错误的。您传递的是要创建的数组的大小而不是所需的内存大小。

例如,您需要一个mytype类型的2元素数组,您需要此代码:

 newarray = malloc(2 * sizeof(mytype));

然后

 newarray[0] 

 newarray[1]

为mytype留出空间。