我正在创建链接列表类型的数据结构,但不完全是。到目前为止,我有以下内容,但是问题是,只有第一个链接完成此方法后,第一个链接就消失后的链接。这里有什么问题?
//Global Vars
m_p H = NULL; //m_p is the struct
func(){
/* .... */
H = malloc(sizeof(m_r));
H->next = NULL;
H->previous = NULL;
m_p p = H;
for(i = 0; i < nLists; i++){
m_p n = malloc(sizeof(m_r));
n->next = NULL;
n->previous = p;
p->next = n;
p = p->next;
}
//if I iterate through the links here, they all print out fine
m_p x = H;
while(x != NULL){
printf("%d ", x->data);
x = x->next;
}
}
由于H是一个全局变量,因此链接不应该保持原样吗?当我尝试循环浏览同一文件中另一个函数中的链接时,它们不存在,只有第一个是。我在做什么错?
编辑:我省略了我在每个结构中设置数据字段以保持代码简洁的部分。
编辑2:这是另一个文件中的函数,这是错误发生的地方:
extern m_p H;
m_p func2(int s) {
int n_s = ALIGN(s);
m_p p = H;
while(p != NULL ){
printf("1. %d n", p->data);
p = p->next; //this is always NULL even if there were more than one node previously in func()
if(p == NULL) printf("LINK NOT PRESENT n");
}
/* ... */
}
这也是我的结构的样子:
typedef struct m{
struct m *next;
struct m *previous;
int data;
} m_r, *m_p;
据我所知,您的代码看起来不错。BluePixy提供的代码,因此我必须同意BluePixy。您的问题可能在其他地方。这是我在计算机上测试的代码(这与BluePixy的代码非常相似(。
list.h
struct node {
struct node *previous, *next;
int data;
};
void linkedList();
void anotherFunction();
void freeMemory();
list.c
#include <stdlib.h> // malloc, free
#include <stdio.h> // printf
#include "list.h"
// Global variable
struct node *m_root;
void linkedList(){
m_root = malloc(sizeof(struct node));
m_root->data = -1;
m_root->next = NULL;
m_root->previous = NULL;
int i;
int n = 10;
struct node *prev = m_root;
struct node *next;
for(i=0;i<n;i++){
next = malloc(sizeof(struct node));
next->data = i;
next->previous = prev;
prev->next = next;
prev = prev->next;
}
printf("Within linkedListn");
struct node *iter = m_root;
while(iter!=NULL){
printf("%d ",iter->data);
iter = iter->next;
}
printf("n");
}
void anotherFunction(){
printf("Within anotherFunctionn");
struct node *iter = m_root;
while(iter!=NULL){
printf("%d ",iter->data);
iter = iter->next;
}
printf("n");
}
void freeMemory(){
printf("Freeing memoryn");
struct node *current = m_root;
struct node *next;
while(next!=NULL){
next = current->next;
free(current);
}
m_root->next = NULL;
m_root = NULL;
}
extern.c
#include <stdio.h>
#include "list.h"
extern struct node *m_root;
void anotherFileFunction(){
struct node *iter = m_root;
while(iter!=NULL){
printf("1. %dn",iter->data);
iter = iter->next;
}
}
int main(){
linkedList();
anotherFileFunction();
freeMemory();
anotherFileFunction();
printf("Done!n");
return 0;
}
输出是:
Within linkedList
-1 0 1 2 3 4 5 6 7 8 9
1. -1
1. 0
1. 1
1. 2
1. 3
1. 4
1. 5
1. 6
1. 7
1. 8
1. 9
Freeing memory
Done!