【发布时间】:2013-09-27 23:10:58
【问题描述】:
对于如何从函数返回指向字符串(基本上是二维数组)的指针数组,我感到困惑和无能。
我在这段代码中所做的(或即将做的)是,首先插入单词/名称,然后将其存储在数组中,并输入数字“n”。然后我将这个数组和数字传递给函数,然后他们从数组中提取了最后 'n' 个名称/单词并在 main 中打印出来。
这是我的代码:
#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 的学习阶段。
【问题讨论】:
-
您不能返回本地自动数组,这是未定义的行为。看看
malloc()(不要转换它的返回值),或者让你的函数填充一个作为参数传递给它的数组。 -
@H2CO3 即使我做 static char *f[5] ,我也会遇到同样的问题。有没有其他选择?顺便说一句,您提供的链接我觉得它完全不同,因为我强调解决此问题的指针方法。我希望我足够清楚
-
除了
static和malloc()?不,没有。我可以向您保证,这很简单,如果您遇到错误,您应该在谷歌上搜索错误消息以了解其含义,然后相应地调整您的代码,直到它工作为止。 -
main必须返回int。
标签: c arrays string function pointers