我对如何从函数返回指向字符串(基本上是二维数组)的指针数组感到困惑和无能。
我在这段代码中所做的(或即将做的)是,首先插入单词/名称,然后将其存储在数组中,并输入数字“n”。然后我将这个数组和数字传递给函数,然后他们从数组中提取了最后的“n”个名字/单词并在主文件中打印出来。
这是我的代码:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
char** fun(char *s[5],int no)
{
char *f[5];
int i,j=0;
for(i=5-no;i<5;i++)
{
f[j]=(char*)malloc(strlen(s[i])+1);
strcpy(f[j],s[i]);
j++;
}
/*for(j=0;j<no;j++) //I did it just to check whether 'f' stores the last 'n' names.
printf("\n%d. %s",j+1,f[j]);*/
return f;
}
void main()
{
char *name[5],*str,*list[5];
int i,n;
clrscr();
printf("Enther the Names of the list : " );
for(i=0;i<5;i++)
{
printf("%d. ",i+1);
str=(char*)malloc(30);
gets(str);
name[i]=(char*)malloc(strlen(str)+1);
strcpy(name[i],str);
free(str);
}
clrscr();
printf("\nEntered Names are : ");
for(i=0;i<5;i++)
printf("\n%d. %s",i+1,name[i]);
printf("\n Enter the no. :");
scanf("%d",&n);
*list=*fun(name,n); // I am little confused as to how should I wrote this ?
for(i=0;i<n;i++)
printf("\n%d. %s",i+1,list[i]);
getch();
}
假设我给输入为:
1.the
2.there
3.this
4.that
5.therefore
输入编号:3
输出:
1.this
2.<Some special characters>
3.<Some special characters>
我会对使用指针方法的方法更感兴趣。PS:我正在使用 Turbo C/C++ IDE,因为我处于 C 的学习阶段。