【发布时间】:2019-07-12 00:56:22
【问题描述】:
我正在尝试做一些功课,但不知道从哪里开始,或者我是否走在正确的道路上。给我这个程序的目的是创建一个函数来创建一个新节点,该节点的数组大到足以容纳输入“计数”。从那里我假设我应该输出创建的节点。
我尝试使用不同的指针以多种方式设置节点,但我不确定如何正确初始化“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);
^~~
【问题讨论】:
-
您没有在
create_node中为newnode->values分配任何内容。 -
另外,因为这是C,所以不需要强制转换malloc的结果
-
size什么都不是。应该是sizeof。你有一个编译错误。这是我回答的错误,对不起, -
啊,我明白了,不用担心。它现在正在编译和运行,没有任何问题,但据说如果我做的一切正确,它会打印“ok”。我会再玩一些,看看我能从这里到达哪里。谢谢!我肯定在设置初始化时遇到了麻烦。
-
没问题。除了接受,您还可以投票,顺便说一句
标签: c visual-studio-code linked-list