0

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

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

4

2 回答 2

0

正如H2CO3指出的那样,定义funas fun(list, name, n);wherelist是您的字符串输出列表。list把from传过去main(),往里填fun()

于 2013-09-23T06:13:01.127 回答
0

您不能在本地定义 char 的指针数组(它将在堆栈上分配它。它的范围仅在该函数内部)并在全局范围内使用它。在 fun() 你可以使用 char f = (char )malloc(sizeof(char*[5])); (在堆上分配内存,您可以全局使用它)而不是 char *f[5];

代码应该是:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <malloc.h>
char** fun(char *s[5],int no)
{
    char **f = (char**)malloc(sizeof(char*[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;
        int i,n;

        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);
        }

        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();
    }
于 2013-09-23T13:19:24.927 回答