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

C语言中如何将getopt参数写入字符串?代码输出异常求助

问题分析与修复方案

代码存在的核心问题

  • 字符数组未初始化:fsrt、sstr、tstr三个字符数组声明后未初始化,内存中留存随机垃圾数据。strcat函数要求目标字符串必须以\0(字符串结束符)结尾,否则会从数组起始位置读取直到找到第一个\0,进而把内存中的垃圾内容混入输出,导致出现奇怪符号。
  • 逻辑冗余:三个独立if判断可优化为else if,减少不必要的条件检查(非直接报错原因,但能提升代码效率)。

修复后的代码

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

int main(int argc, char *argv[])
{
    // 初始化字符数组为空字符串,确保以'\0'结尾
    char fsrt[100] = "", sstr[100] = "", tstr[100] = "";
    int rez = 0;
    while ( (rez = getopt(argc, argv, "f:s:l:")) != -1 )
    {
        if (rez == 'f') {
            strcat(fsrt, optarg);
        } else if (rez == 's') {
            strcat(sstr, optarg);
        } else if (rez == 'l') {
            strcat(tstr, optarg);
        }
    }

    printf("%s %s %s\n", fsrt, sstr, tstr);

    return 0;
}

额外优化建议

如果仅需将optarg内容赋值给数组,用strcpy替代strcat更直接(因数组初始为空,效果完全一致):

// 以-f参数为例
strcpy(fsrt, optarg);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:45:31