这是多个字符串,进行逆序输出,但保证字符串内部不被打乱的程序。
#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]并没有指向任何空间有帮助望采纳~
#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;
}