值未分配给structPointers

如何解决值未分配给structPointers

当我尝试为*temp赋值时,它没有赋值(在编译时,它不显示printf,并且按printf看不到任何赋值)。为什么呢我该如何处理有关指针的更多信息(从IDE中查看它们在外部应用程序中所引用的位置??)

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #define INT_SIZE sizeof(int) * 8
    
    typedef struct Node Node;
    struct Node
    {
        int value;
        Node *next;
    };
    
    
    typedef struct LinkedList
    {
        Node *head;
    }LinkedList;
    
    
    void Insert(LinkedList **lst,int data)
    {
        Node *temp = malloc(sizeof(Node)); 
        //Check's if is the first Node.
        if ((*lst)->head->next== NULL)
        {       
            (*lst)->head->next = temp;  
            temp->value = data;
            printf("Ok");   
            temp->next = NULL;
        }
    }

还有我的主要功能:

int main()
{
    LinkedList *list = malloc(sizeof(LinkedList)); //Create new linkedlist
    list->head->next = NULL; //Define the head object
    Insert(&list,20);
    return 0;
}

解决方法

您动态分配了一个列表

LinkedList *list = malloc(sizeof(LinkedList));

,但是其数据成员head尚未初始化。结果,下一条语句

list->head->next = NULL;

调用未定义的行为,因为使用了变量head,其值不确定。

没有任何意义将函数Insert的第一个参数声明为类型LinkedList **lst,即使用两个间接访问原始列表的类型。最好像这样声明函数

int Insert( LinkedList *list,int data );

要检查列表是否为空,您必须至少像这样写

    if ( ( *lst )->head == NULL )

此外,如果列表不为空,则您的函数不执行任何操作。

请注意,通常应检查新节点的分配是否成功。

可以通过以下方式定义功能

int Insert( LinkedList *list,int data )
{
    Node *temp = malloc( sizeof( Node ) );
    int success = temp != NULL;

    if ( success )
    {       
        temp->value = data;
        temp->next  = list->head;
        list->head = temp;
    }

    return success;
}

无需动态分配列表本身。你可以写

LinkedList list = { .head = NULL };

Insert( &list,20 );

请注意,您需要编写一个释放所有分配的内存的函数。例如

void Delete( LinkedList *list )
{
    while ( list->head != NULL )
    {
        Node *temp = list->head;
        list->head = list->head->next;
        free( temp );
    }
}

这是一个演示程序。

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

typedef struct Node Node;
struct Node
{
    int value;
    Node *next;
};
    
    
typedef struct LinkedList
{
    Node *head;
} LinkedList;

int Insert( LinkedList *list,int data )
{
    Node *temp = malloc( sizeof( Node ) );
    int success = temp != NULL;

    if ( success )
    {       
        temp->value = data;
        temp->next  = list->head;
        list->head = temp;
    }

    return success;
}

void Delete( LinkedList *list )
{
    while ( list->head != NULL )
    {
        Node *temp = list->head;
        list->head = list->head->next;
        free( temp );
    }
}

void Display( const LinkedList *list )
{
    for ( const Node *current = list->head; current != NULL; current = current->next ) 
    {
        printf( "%d -> ",current->value );
    }
    
    puts( "null" );
}

int main(void) 
{
    LinkedList list = { .head = NULL };
    
    const int N = 10;
    
    for ( int i = N; i != 0; i-- )
    {
        Insert( &list,i );
    }
    
    Display( &list );
    
    Delete( &list );
    
    return 0;
}

其输出为

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null

如果您的编译器不支持指定的初始化,则代替此声明

    LinkedList list = { .head = NULL };

您可能只是写

    LinkedList list = { NULL };

如果您想在函数Insert看起来如下时将新节点附加到列表的末尾

int Insert( LinkedList *list,int data )
{
    Node *temp = malloc( sizeof( Node ) );
    int success = temp != NULL;

    if ( success )
    {       
        temp->value = data;
        temp->next  = NULL;
        
        Node **current = &list->head;
        while ( *current ) current = &( *current )->next;
        
        *current = temp;
    }

    return success;
}
,

您的代码中有很多错误

主要:

LinkedList *list = malloc(sizeof(LinkedList)); //Create new linkedlist
list->head->next = NULL; //Define the head object

是错误的,因为list->head未初始化,因此设置list->head->next的行为未定义

还有一个逻辑问题,一个空列表为空=>没有节点,正确的初始化为:

list->head = NULL;

插入时:

if ((*lst)->head->next== NULL)

同样,如果由于(*lst)->head为NULL(在上述更正之后)而导致列表为空时,这是无效的。

也没有 else 分支,该函数必须始终插入新节点。

要以正确的方式实现,需要知道必须在哪里插入,您的列表是fifo,lifo还是根据值对节点进行了排序?

假设始终将一个节点插入头部:

void Insert(LinkedList **lst,int data)
{
    Node *temp = malloc(sizeof(*temp)); 

    temp->value = data;
    temp->next = (*lst)->head;
    (*lst)->head = temp;
}

请注意,使用双指针是没有用的,您可以使用:

void Insert(LinkedList *lst,int data)
{
    Node *temp = malloc(sizeof(*temp)); 

    temp->value = data;
    temp->next = lst->head;
    lst->head = temp;
}

int main()
{
    LinkedList *list = malloc(sizeof(*list)); //Create new linkedlist
    list->head = NULL;
    Insert(list,20);
    return 0;
}

最后:

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

typedef struct Node {
  int value;
  struct Node *next;
} Node;
    
    
typedef struct LinkedList {
  Node *head;
} LinkedList;

void Insert(LinkedList *lst,int data)
{
    Node *temp = malloc(sizeof(*temp)); 

    temp->value = data;
    temp->next = lst->head;
    lst->head = temp;
}

void pr(const LinkedList *lst)
{
  const Node * l = lst->head;
  
  while (l != NULL) {
    printf("%d ",l->value);
    l = l->next;
  }
  putchar('\n');
}

int main()
{
    LinkedList *list = malloc(sizeof(*list)); //Create new linkedlist
    list->head = NULL;
    Insert(list,20);
    pr(list);
    Insert(list,10);
    pr(list);
    return 0;
}

编译和执行:

/tmp % gcc -Wall l.c
/tmp % ./a.out
20 
10 20 
/tmp % 
,

您正在尝试使用内存而不分配内存。 LinkedList *指向有效的(动态分配的)结构,但是head指向无处(Node没有保留空间),因此一旦尝试编写它,就会出现段错误。 / p>

您有两个选择:

  • malloc一样,为head的{​​{1}}保留空间
  • 不将LinkedList声明为指针,并在其中分配其空间 堆栈/全局(head)。

Node head相同,请考虑是否要让指针指向其余代码中已经有效的Node *next;

另一个问题是您没有释放动态内存,不确定代码是否只是示例还是内存泄漏。

,

您尚未为let hours = 2; let minutes = 3; let seconds = 20; function n(n){ return n > 9 ? "" + n: "0" + n; } console.log(n(hours) + ':' + n(minutes) + ':' + n(seconds));分配内存,这意味着您无法访问或修改list->head

您应该首先为列表的开头分配内存:

list->head->next

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-