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

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

#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[]这个指针字符串组里似乎卡死了,有没有大师指点迷津

你最后一次输入似乎没有存到数组里面
啊发现问题了
因为你的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

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632