793416 2017-10-30 14:40 采纳率: 100%
浏览 1472
已采纳

以下代码怎样改正(C语言字符串问题)

 #define STDC_WANT_LIB_EXT1 1
#include <stdio.h>
#include <string.h>

int main(void)
{
    char preamble[] = "The joke is:\n\n";
    char str[][40] = {
                        "My dog has\'t got any nose.",
                        "How does your dog smell then?\n",
                        "My dog smells horrible.\n"
    };
    unsigned int strCount = sizeof(str) / sizeof(str[0]);

    unsigned int length = 0;
    for (unsigned int i = 0; i < strCount; ++i)
    {
        length += strnlen_s(str[i], sizeof(str[i]));
    }

    **char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1];**

    if (strncpy_s(joke, sizeof(joke), preamble, sizeof(preamble)))
    {
        printf("Error copying preamble to joke.\n");
        return 1;
    }

    for (unsigned int i = 0; i < strCount; ++i)
    {
        if (strncat_s(joke, sizeof(joke), str[i], sizeof(str[i])))
        {
            printf("Error copying string str[%u].", i);
            return 2;
        }
    }
    printf("%s", joke);
    return 0;


}



错误信息:
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2057: 应输入常量表达式
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2466: 不能分配常量大小为 0 的数组
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2133: “joke”: 未知的大小
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(23): warning C4034: sizeof 返回 0
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(31): warning C4034: sizeof 返回 0

  • 写回答

2条回答 默认 最新

  • threenewbee 2017-10-31 00:50
    关注

    char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1];
    这个写法,在一些编译器上可以,另一些不可以。gcc就可以。
    在不允许数组申明中使用变量的编译器,可以用malloc动态分配。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序