gpt4 book ai didi

c - 返回指向字符串的指针数组

转载 作者:行者123 更新时间:2023-11-30 17:47:20 24 4
gpt4 key购买 nike

我对如何从函数返回指向字符串(基本上是二维数组)的指针数组感到困惑和无能为力。

我在这段代码中所做的(或即将要做的)是,首先插入单词/名称,然后将其存储在数组中,并输入数字“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 的学习阶段。

最佳答案

正如H2CO3所指出的,将fun定义为fun(list, name, n);,其中list 是字符串的输出列表。从 main() 传递 list,将其填充到 fun() 中。

关于c - 返回指向字符串的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com