【发布时间】:2018-01-14 04:09:58
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
char *readline()
{
char s[256],*ds;
printf("Give string: ");
gets(s);
ds = (char *) calloc(strlen(s)+1,sizeof(char));
strcpy(ds,s);
return ds;
}
main()
{
char *s1,*s2;
int a,b;
s1=readline();
printf("Start:");
scanf("%d",&a);
printf("End:");
s2=(char*)realloc(s1,b-a);
puts(s2);
return 0;
}
我有这段代码,我想调整 s1 数组的特定单元格的大小,这些单元格由变量 a 和 b 确定。
例如。如果我给出字符串"Hello" 和整数a=2 和b=4,那么我希望程序打印"ell"。
【问题讨论】:
-
为什么需要
realloc这样做? -
如果有其他方法那就没问题了。