如何初始化结构值并正确输出结构

时间:2019-07-12 00:56:22

标签: c visual-studio-code linked-list

我正在尝试一些家庭作业,不确定从哪里去,或者我是否在正确执行此操作的正确道路上。这个程序是给我的,目的是创建一个函数来创建一个新节点,该节点的数组足以容纳输入的“计数”。从那里开始,我假设我应该输出创建的节点。

我尝试使用不同的指针以多种方式设置节点,但是我不确定如何正确初始化'newnode'。并且每次我尝试使用输入“ count”,例如“ newnode-> array_length = count;”时我遇到了分段错误,但是我不明白为什么,如果将count输入到函数中,它在它的范围内不可用吗?

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<assert.h>

typedef struct node {
    struct node* previous;
    struct node* next;
    int array_length;
    int* values;
} node;

//creates a new node with an array large enough to hold `count` values
node* create_node(int count) {
//your code here:
    node* newnode;
    newnode = (node*) malloc(sizeof(node));
    newnode->array_length = count;
    newnode->values;
    newnode->next=NULL;
    newnode->previous=NULL;

    return newnode;
}

void append(node* a, node* b) {
    assert(a);
    assert(b);
    a->next = b;
    b->previous = a;
}

int main() {
    node* a = create_node(10);

    assert(a->array_length == 10);
    assert(a->next == NULL);
    assert(a->previous == NULL);

    node* b = create_node(20);

    assert(b->array_length == 20);
    assert(b->next == NULL);
    assert(b->previous == NULL);

    append(a, b);

    assert(a->next == b);
    assert(b->previous == a);
    assert(a->previous == NULL);
    assert(b->next == NULL);

    for(node* cur = a; cur != NULL; cur = cur->next) {
        for(int i = 0; i < cur->array_length; i++) {
            cur->values[i] = i;
        }
    }
}

编译错误:

problem2.c: In function ‘create_node’:
problem2.c:20:30: warning: implicit declaration of function ‘size’ [-Wimplicit-function-declaration]
     newnode->values = malloc(size(int) * count);
                              ^~~~
problem2.c:20:35: error: expected expression before ‘int’
     newnode->values = malloc(size(int) * count);
                                   ^~~

1 个答案:

答案 0 :(得分:1)

您没有为values分配内存。默认情况下,将其设置为之前存在的任何内存,这可能是无效的指针。当您尝试访问values时,这将导致段错误。

//creates a new node with an array large enough to hold `count` values
node* create_node(int count) {
//your code here:
    node* newnode = malloc(sizeof(node));
    newnode->array_length = count;
    newnode->values = malloc(sizeof(int) * count);   // malloc memory for values
    newnode->next = NULL;
    newnode->previous = NULL;

    return newnode;
}