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

C语言链表开发问题:strcpy复制异常及switch标签声明报错

问题解决:链表实现中的编译错误与字符串复制问题

1. 编译错误:case标签后不能直接放置变量声明

错误信息 a label can only be part of a statement and a declaration is not a statement 是因为C语言语法规定:case 属于标签,标签后面必须紧跟语句,不能直接放置变量声明(比如原代码里的char letter1[] ="Whisky\n";)。

解决方法:

  • 直接省略多余的临时字符数组,把字符串常量作为strcpy的第二个参数,完全不需要临时变量;
  • 如果必须保留变量声明,给每个case的代码块加上大括号{},将声明包裹在复合语句中,让编译器识别为语句块的一部分。

2. 字符串复制问题

原代码中strcpy看似失效,本质是编译错误导致代码无法正常运行,并非strcpy本身的问题。原代码里的临时字符数组属于冗余写法,简化后即可正常完成字符串复制。

修正后的完整代码

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

struct fest {
    struct fest* next;
    char Name[10];
    int  Zahl;
};

struct fest* anker = NULL;

int main (void){
   
    for(int i=0; i< 4; i++)
    {
        struct fest* zeiger;
        if((zeiger=malloc(sizeof(struct fest)))!=NULL)
        {
            zeiger->Zahl = i+1;
            
            switch(i){
                case 0: 
                    strcpy(zeiger->Name, "Whisky\n"); 
                    break;
                case 1: 
                    strcpy(zeiger->Name, "Tango\n"); 
                    break;
                case 2: 
                    strcpy(zeiger->Name, "Foxtrott\n"); 
                    break;
                case 3: 
                    strcpy(zeiger->Name, "X-Ray\n"); 
                    break;
            }

            zeiger->next = anker;
            anker = zeiger;
        }
    }
    struct fest* abruf= anker;

    while(abruf !=NULL){
        printf("%d %s", abruf->Zahl, abruf->Name); // 原printf多了一个\n,字符串本身已包含换行符,避免重复换行
        abruf = abruf->next;
    }

    // 补充内存释放,避免内存泄漏(学习阶段建议养成该习惯)
    struct fest* temp;
    while(anker != NULL){
        temp = anker;
        anker = anker->next;
        free(temp);
    }

    return 0;
}

额外说明

  • 简化后的代码去掉了冗余的临时数组,直接使用字符串常量传递给strcpy,代码更简洁高效;
  • 补充了链表内存释放逻辑,这是链表实现中重要的环节,避免程序结束后残留内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:54:53