无法创建头指针指向c的新节点?

时间:2016-02-20 22:40:53

标签: c pointers linked-list

说我有以下代码将末端的节点插入到链表中:

int main() {
    struct Node* head = NULL;
    newNode(head, 1);
    newNode(head, 2);
    newNode(head, 3);
    print(head);
    return 0;
}
void newNode(struct Node* head, int val) {
    struct Node* curr_p = head;
    struct Node* new_p = malloc(sizeof(struct Node));
    new_p->data = val;
    new_p->next = NULL;
    if (head == NULL) {
        curr_p = new_p;
        // printf("head %d \n", head->data); 
    }
    else{
        while (curr_p->next != NULL) {
            curr_p = curr_p->next;
        }
        curr_p->next = new_p;
    }
}
void print(struct Node* head) {
    struct Node* curr_p = head;
    while (curr_p != NULL) {
        printf("%d\n", curr_p->data);
        curr_p = curr_p->next;
    }
}

出现错误的原因是在if语句块中head == NULL,头节点指针似乎无法指向新节点。我总是以分段错误结束。有什么理由吗?

2 个答案:

答案 0 :(得分:0)

你没有指明你在哪里得到分段错误,但我强烈猜测你会得到 - printf("head %d \n", head->data);。为什么?因为您的当前代码head为NULL(您从main方法传递的内容)然后您尝试取消引用NULL然后您将分段错误。

您必须只取消引用有效指针。如果指针变量保持NULL或某些未初始化/默认值,则取消引用它将导致分段错误。

下面是固定的IF块。

if (head == NULL) {
    head = new_p;
    printf("head %d \n", head->data); 
} 

答案 1 :(得分:0)

我猜你的错是你将头指针传递给值而不是引用,所以代码没有改变它的值,因为它只是复制了指针 所以你的代码应该是这样的

_, line = reader.read(filenames)

# N.B. Batch size is 2, to match the size of your file.
line_batch, = tf.train.batch([line], batch_size=2)

col1, col2 = tf.decode_csv(line_batch,
                           record_defaults=[tf.constant([],dtype=tf.int32),
                                            tf.constant([],dtype=tf.int32)])

sess.run(tf.initialize_all_variables()
tf.train.start_queue_runners(sess)

print sess.run([col1, col2])  # ==> [1, 3], [2, 4]

并在主

newNode(struct Node** head , int val ) {
struct Node* curr_p = *head;
/*

*/
if(curr_p == NULL ) {
*head = new_p;

}/*....*/
    }

并且结局代码将是

newNode(&head,1)

实际上你不必在打印功能中使用curr_p因为打印功能中的头指针它只是主要功能的头指针的副本所以它不会如果您在打印功能中执行#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node * next; }; void newNode(struct Node** head, int val) { struct Node* curr_p = *head; struct Node* new_p =malloc(sizeof(struct Node)); new_p->data = val; new_p->next = NULL; if ( curr_p == NULL) { *head = new_p; // printf("head %d \n", head->data); } else{ while (curr_p->next != NULL) { curr_p = curr_p->next; } curr_p->next = new_p; } } void print(struct Node* head) { struct Node* curr_p = head; while (curr_p != NULL) { printf("%d\n", curr_p->data); curr_p = curr_p->next; } } int main() { struct Node* head = NULL; newNode(&head, 1); newNode(&head, 2); newNode(&head, 3); print(head); return 0; } 之类的操作,请更改它的值。