You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言开发电话簿应用时链表firstname、lastname字符串无法打印求助

问题排查与修复方案

核心问题说明

你的代码存在多处内存操作和语法错误,直接导致字符串无法正常打印,具体问题如下:

  • 结构体成员定义不合理:number定义为int*指针类型无实际意义,直接使用普通int即可存储手机号数值;firstname、lastname为字符指针但未分配可存储字符串的内存空间,属于野指针,写入数据会触发内存越界。
  • scanf参数传递错误:对于字符指针类型的字符串变量,scanf("%s")直接传入变量本身即可,不需要额外加取地址符&。你当前的写法是把字符串写入了存储指针地址的内存空间,而非存储字符串内容的内存,直接导致字符串数据损坏。
  • 遍历逻辑错误:display函数仅用if判断只会打印链表的第一个节点,需改为while循环才能遍历全链表所有节点;同时你定义display无参数,但调用时传入了start,参数不匹配。
  • 内存分配不完整:getnode仅分配了struct node本身的内存,未给内部的字符串成员分配存储空间;create函数声明返回struct node*但实际无返回值,存在语法隐患。

修复后完整代码

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

// 修改结构体定义,用定长数组存储字符串,number改为普通int
struct node { 
    char firstname[50]; 
    char lastname[50]; 
    int number; 
    struct node *next;
}; 

struct node *start = NULL; 

struct node *getnode() { 
    struct node *p = (struct node *)malloc(sizeof(struct node));
    // 增加内存分配失败校验
    if (p == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    p->next = NULL;
    return p;
}

// 修改display,用while循环遍历全链表
void display() { 
    struct node *temp = start; 
    if(temp == NULL) {
        printf("Please create an entry\n"); 
        return;
    }
    while(temp != NULL) {  
        printf("名:%s \n", temp->firstname); 
        printf("姓:%s \n", temp->lastname); 
        printf("手机号:%d \n\n", temp->number); 
        temp = temp->next; 
    }
} 

void insert() { 
    struct node *temp,*nn; 
    nn = getnode(); 
    temp = start; 
    while(temp->next != NULL) 
    { 
        temp = temp->next; 
    }
    printf("Enter First name:\n"); 
    // 去掉取地址符&,直接传数组名/字符指针
    scanf("%s", nn->firstname); 
    printf("Enter Last name:\n"); 
    scanf("%s", nn->lastname); 
    printf("Enter number:\n"); 
    scanf("%d", &nn->number); 
    temp->next = nn; 
    nn->next = NULL; 
    display();
} 

// 修改返回值为void,匹配实际逻辑
void create() {
    struct node *nn; 
    if(start != NULL) {
        insert(); 
    } else { 
        nn = getnode(); 
        start = nn; 
        printf("Enter First name:\n"); 
        scanf("%s", nn->firstname); 
        printf("Enter Last name:\n"); 
        scanf("%s", nn->lastname); 
        printf("Enter number:\n"); 
        scanf("%d", &nn->number); 
        nn->next = NULL;
        display();
    }
} 

如果你需要动态分配字符串内存而非用定长数组,只需要在getnode中新增对firstname和lastname的malloc分配即可,注意要匹配对应字符串长度,避免内存浪费或越界。

内容的提问来源于stack exchange,提问作者Luke Grech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:45:02