c - 没有强制类型转换错误的链表指针

标签 c linked-list compiler-warnings

我在第 46 行和第 53 行(这两行两边都有双星号)上收到了赋值使指针从整数没有强制转换错误的消息,我一生都无法弄清楚为什么。链表对我来说很陌生,我还不知道它们是如何工作的。

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

struct node_def
{
    int data;
    struct node_def *next;
};
typedef struct node_def node;

node *makeNode (int a);
node *insertFront(node *head,node *new);
void printList(node *head);

int numNodes = 0;

int main()
{
    srand(time(0));
    int r = rand() % 10000;
    int i = 0;

    node *head = NULL;
    node *tmp = NULL;

    printf("How many nodes? ", numNodes);
    scanf("%d", numNodes);
    printf("\n");

    head = insertFront(head, tmp);

    for(i = 0; i < numNodes; i++)
    {
        makeNode(r);
        printList(head);
    }
    printf("\n");

    return 0;
}
node *makeNode (int a)
{
    node *new = malloc(sizeof(node));
    **new = a;**

    return new;
}
node *insertFront(node *head, node *new)
{

    **new->data = head;**
    new->next = new;

    return 0;
}
void printList(node *head)
{
    int j = 0;
    for(j = 0; j < numNodes; ++j)
    {  
        while (head != NULL)
        {
            printf(" %4d", head->data);
            head = head->next;
        }
        if(j % 10 == 0)
            printf("\n");
    }
    return;
}

new = a 旨在创建新节点并为其分配 0 - 9999 之间的随机数。

最佳答案

您尝试将 r 分配给 new,但 new 是一个结构。 您创建了一个指向 struct 的指针:node *new 您要做的是将 r 分配给 new->data,它是一个 int。

node *insertFront(node *head, node *new)
{
**new->data = head;** // ** is meaningless 
new->next = new; // new is a reserved key word, don't use it this way
return 0;
}

您尝试做的是将 NULL 指针作为列表的头部。 只需在 makeNode 函数中将元素插入其中即可。 像这样插入:

void createNode(node *head)
{
    Node *new_node = malloc(sizeof(Node*));
    new_node->data = rand() % 100000;
    new_node->next = NULL;
    if(head == NULL)
        head = new_node;
    else if(head != NULL)
        //Here you have to adapt your list, search (linked list crud functions)
}

您对指针是什么没有很好的理解。 希望对老哥有帮助

关于c - 没有强制类型转换错误的链表指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43301274/

相关文章:

c - 在编译时从 __VA_ARGS__ 确定参数类型

c - 对于 Z3 中的所有量词

java - LinkedList队列实现

c - 如何正确打印链表成员

c++ - 如何将 head 从 main 传递到 addNode 函数? (通过结构实现 LinkedList)

c++ - 编译器警告 : lambda return type cannot be deduced

python - 如何从 Python 脚本访问 C 全局变量

c - 使用位操作查找最小值

c - 警告 "format not a string literal and no format arguments"未出现在最新的 gcc 版本中

c++ - g++ C++0x 枚举类编译器警告