c - C 中的结构/链表/指针/字符串

标签 c string pointers struct linked-list

所以我在使用 C 中的链表时遇到了一些麻烦。总的来说,我了解了概念和算法,因为我已经在 J​​ava 中学习了这些想法。但在 C 中似乎是另一回事,因为我们还考虑了内存分配。

无论如何,我这里有这段代码:

while (curr != NULL) {
    printf("%s\n", (*curr).name);
    curr = (*curr).next;
}

其中 curr 是一个 struct Student 并且 Student 的“属性”之一是 name。所以假设我已经将我的节点添加到列表中。当我执行上面的命令时,我似乎得到了完全相同的名字。下面是我将节点添加到链表中的代码:

void insertNode(char *name, int idNum, char sex) {

    struct Student *s;
    s = malloc(sizeof(struct Student));

        //not entirely sure if this is the right way to do it
    if (s == NULL) { 
        printf("Memory allocation failed.");
        return;
     }

    (*s).name = name;
    (*s).idNum = idNum;
    (*s).sex = sex;

    (*s).next = head;        //head is the start of the list
    head = s;         //inserting the node at the beginning of the list

    curr = head;     //place the current pointer at the start of list
}

基本上我对 intchar 似乎没有问题。如果我的列表中有 {"Alice", 1000, 'F'} -> {"Bob", 1001, 'M'} -> {"Charlie", 1002, 'M'} ,我注意到添加到列表中的姓氏 Alice 将被打印出来。所以打印输出将是:

Alice
Alice
Alice

我是不是做错了什么?有什么我想念的吗?我是 C 的初学者,仍在自学。非常感谢您的帮助和建议!

最佳答案

您需要跟踪头部指针。

这里是完整的工作代码:

#include <stdio.h>
#include <stdlib.h>


struct Student
{
    char * name;
    int idNum;
    char sex;
    struct Student * next;
};

struct Student * head=NULL;

struct Student *
insertNode (char *name, int idNum, char sex)
{

  struct Student *s;
  s = malloc (sizeof (struct Student));

  if (s == NULL)
    {
      printf ("Memory allocation failed.");
      return NULL;
    }

  (*s).name = name;
  (*s).idNum = idNum;
  (*s).sex = sex;


  (*s).next = head;     //head is the start of the list

  head = s;

  return head;          
}


int
main ()
{
    insertNode("Alice", 1, 'F');
    insertNode("Peter", 2, 'M');
    insertNode("Mike", 3, 'M');


  while (head != NULL)
    {
      printf ("%s\n", (*head).name);
      head = (*head).next;
    }

}

输出:

Mike
Peter
Alice

但是,仍然可以在您的代码中进行大量改进。特别是,符号 (*s).name 在 C 中有一个简写形式,即 s->name 更简洁。您还可以避免使用全局 head 变量,而是传递它的指针,以便可以在两次调用之间维护其更改的值。

关于c - C 中的结构/链表/指针/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49547455/

相关文章:

c - C中的简单堆栈程序

python - 检查字符串是否在python中按字母顺序排列

链表中的 C 指针

java - Java ArrayList<String> 的紧凑替代品

c - 指针移动 cs[1] 和 *cs++ 有什么区别

c++ - 清除指针 vector

c - 超出数组最大索引的未定义行为

c - 测量 C 中函数所花费的时间始终为 0.000000

c - 简化(并使其更清晰)逻辑条件

string - 在元组列表上使用 Map 并将其打印为 Erlang 中的平面字符串