1

嗨,我是 C 新手,我正在努力让链表工作我不得不使用全局变量,因为我无法更改被调用函数的参数。我声明结构和两个全局指针来跟踪根地址和最后一个地址,就像这样。

struct node {
  char* pointer;
  struct node *next;
};

struct node** rootNode;
struct node** lastNode;

然后在函数内部我 malloc 一个新结构并尝试设置列表中的第一个节点。为了尝试保存该节点的位置,我想我正在将全局指针 lastNode 分配给 root 的指针。

struct node *root = malloc(sizeof(struct node));
...
root->pointer=ptr;
root->next = 0;
    rootNode = &root;
lastNode = &root; 

然后我尝试通过分配另一个节点来添加其他节点,然后使用存储在我的 lastNode 指针中的地址链接前一个节点。

struct node *newNode = malloc(sizeof(struct node));

newNode->pointer=ptr ;
(*lastNode)->next = newNode;
newNode->next = 0;
lastNode = &newNode;

然而,这似乎并没有真正起作用。当我运行以下程序时,程序匹配列表中的前两项,但之后为所有节点返回 null。我已经坚持了 2 天了,任何帮助都将不胜感激:)

struct node* test;
test = (*rootNode);
enter code here
while (test) {
       if (test->pointer == ptr) {
       printf("MATCH!!");
       notFound = 0;
       break;
       }
    else {
    test = test->next;
    }
}

编辑有几个人要求我提供更多代码。这是我想在其中创建链接列表的函数。它在我的程序运行时被多次调用,并且每次调用它时我都试图将一个新节点添加到我的链表中。我还在顶部包含了全局变量。

struct node** rootNode;
struct node** lastNode;
int firstRun = 1;

struct node {
char* pointer;
struct node *next;
};

void malloc(size_t sz) {

size_t maxSize = (size_t)-1;  
char * payloadPtr = NULL;

if (sz > maxSize - sizeof(struct node)+sizeof(int)) {
return ptr;
  }

  if (firstRun) {

struct node *root = malloc(sizeof(struct node));

ptr = malloc(sizeof(size_t)+sz);

if (ptr == NULL) {
    return ptr;
    }
memcpy(ptr, &sz, sizeof(int));
payloadPtr = ptr+1;
root->pointer=payloadPtr; 
root->next = 0;
rootNode = &root;
lastNode = &root;
firstRun = 0;

  }
  else { 
struct node *newNode = malloc(sizeof(struct node));
ptr = malloc(sizeof(size_t)+sz);

if (ptr == NULL) {
  return ptr;
}
memcpy(ptr, &sz, sizeof(int));
payloadPtr =ptr+1;
newNode->pointer= payloadPtr; 
(*lastNode)->next = newNode;
newNode->next = 0;
lastNode = &newNode;                
}

return payloadPtr;
}
4

1 回答 1

0

There's a little clarification about changing the parameters into a function. In C you can only pass by pointers on function calls so if you want to modify the value of a struct node - you pass it like struct node * in the function. Similarly if you want to change the value of a struct node * in the function (as in allocate it or delete it) you may want to pass it like struct node **.

Your function prototype will probably have to look like this:

void addNode(struct node** root, char* value)

But you can also make that root node a local and also just a struct node * instead of struct node **. And then simply call it like:

addNode(&root, value);

于 2013-10-01T14:11:46.073 回答