C程序设计(第四版) 谭浩强 习题8.19(1) 个人设计
习题 8.19(1) 编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。
代码块:
#include <stdio.h>
#include <stdlib.h>
char *news(char *s[], int n);
int main()
{
char *str[10], **p;
int i;
printf("Please enter array number: ");
scanf("%d", &i);
*str=news(str, i);
for (p=str, printf("Please enter %d strings: ", i); p<str+i; scanf("%s", *p++));
for (p=str, printf("Result: "); p<str+i; printf("%s ", *p++));
printf("\n");
return 0;
}
char *news(char *s[], int n)
{
for (int i=0; i<n; s[i++]=(char *)malloc(20*sizeof(char)));
return *s;
}