I am confused and clueless as how can I return an Array of pointers to a String(Basically 2D array) from a function.
What I did(or about to do )in this code is , first insert words/names and then stored it in the array and also input the number 'n'. Than I passed this array and number into the function and their extracted the last 'n' names/words from the array and print that in the main.
Here is my code :
#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();
}
Suppose I gave the Input as :
1.the
2.there
3.this
4.that
5.therefore
Enter the No.: 3
Output:
1.this
2.<Some special characters>
3.<Some special characters>
I would more interested in the method which uses the pointer approach . PS: I am Using Turbo C/C++ IDE as I am in a Learning phase of C .