lausadfa 2022-03-02 18:27 采纳率: 50%
浏览 35
已结题

多个字符串,进行逆序输出,但保证字符串内部不被打乱的程序

这是多个字符串,进行逆序输出,但保证字符串内部不被打乱的程序。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable:4996)
int main()
{
    int i, n;
    char* color[20];
    char str[15];
    i = 0;
    printf("enter n:");
    scanf_s("%d", &n);
    printf("please input words:");
    scanf_s("%s", str,sizeof(str));
    //color[0] = str;
    //puts(color[0]);
    //printf("%d", strlen(str));
    while (i < n-1) {
        color[i] = (char*)malloc(sizeof(char) * (strlen(str) + 1));
        strcpy(color[i],str);
        printf("%d", i);
        i++;
        printf("next");
        scanf_s("%s", str,sizeof(str));

    }
    printf("ouput");
    for (i = n - 1; i >= 0; i--) {
        printf("%s  ", color[i]);
        free(color[i]);
    }
    return 0;
}

在执行操作的时候,在最后的输出总是没有,color[]这个指针字符串组里似乎卡死了,有没有大师指点迷津

  • 写回答

2条回答 默认 最新

  • 关注

    你最后一次输入似乎没有存到数组里面
    啊发现问题了
    因为你的while终止条件和下面print的i的初值不对应,导致color[i-1]并没有指向任何空间
    有帮助望采纳~

    img


    代码整体调整后如下:

    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #pragma warning(disable : 4996)
    int main()
    {
        int i, n;
        char *color[20];
        char str[15];
        i = 0;
        printf("enter n:");
        scanf_s("%d", &n);
    
        // color[0] = str;
        // puts(color[0]);
        // printf("%d", strlen(str));
        printf("please input words:");
        while (i <= n - 1)
        {
    
            scanf_s("%s", str, sizeof(str));
            color[i] = (char *)malloc(sizeof(char) * (strlen(str) + 1));
            strcpy(color[i], str);
            printf("%d", i);
            i++;
            printf("next\n");
            // scanf_s("%s", str, sizeof(str));
        }
        printf("ouput");
        for (i = n - 1; i >= 0; i--)
        {
            printf("%s  ", color[i]);
            free(color[i]);
        }
        return 0;
    }
    

    img

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

报告相同问题?

问题事件

  • 系统已结题 3月10日
  • 已采纳回答 3月2日
  • 创建了问题 3月2日

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计