【发布时间】:2017-12-26 05:58:05
【问题描述】:
我正在编写一个简单的代码,它接受来自用户的任意长度的字符串并显示它。但是我的代码没有正确执行它,因为它接受了字符串但没有正确打印它。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
int i,len;
static int n=5;
char a[20];
char **s;
s=malloc(5*sizeof(char));
char *p;
for(i=0;i<n;i++)
{
scanf("%s",a);
if(*a=='1') /*to exit from loop*/
{
break;
}
len=strlen(a);
p=malloc((len+1)*sizeof(char));
strcpy(p,a);
s[i]=p;
if(i==n-1)
{
s=realloc(s,(5+i*5)*sizeof(char));
n=5+i;
}
}
for(i=0;i<n-1;i++)
{
printf("%s ",s[i]);
}
free(p);
p=NULL;
return 0;
}
【问题讨论】:
-
I am writing a simple code which accepts a string from the user of any length and just displays it....你在这里做了很多工作... -
“我不知道这段代码出了什么问题?” - 仅仅一个问号不会把这句话变成一个问题。阅读this post about debugging。
-
你想
accepts a string from the user of any length,但你只有一个19个字符的数组 -
fgets比scanf更有利于您在此处所做的事情(通常在涉及用户输入的任何时候都是这种情况) -
无意义的问题标题减一分。