【问题标题】:How to return an array of structure by reference?如何通过引用返回结构数组?
【发布时间】:2017-04-25 16:25:55
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct data{
    char name[20];
    char lastname[25];
    int age;
}person;

void insert(person *p,int *num);
int main()
{
    int num;
    person p;
    insert(&p,&num);
    printf("Name: %s",p[0].nome); /* Here i would print the first struct by 
     my array, but: is not array or not pointer Why?? */


}

void insert(person *p, int *num)
{
    int dim;
    person *arr;
    printf("Insert how many people do you want? ");  /* How many index the 
    array should have */
    scanf("%d",&dim);
    arr = (person *) malloc(dim*sizeof(person));   /* I'm not sure for 
    this explicit cast. */

for(int i = 0; i < dim; i++)
{
    printf("Insert name: ");
    scanf("%s",arr[i].name);
    printf("Insert lastname: ");
    scanf("%s",arr[i].lastname);
    printf("Insert age:': ");
    scanf("%d",&arr[i].age);
}
*num = dim;
*p = *arr;
}

我试过了:`person *insert(int *num)

它的工作原理,但如何传递一个数组引用?`

这个程序应该问你想插入多少人(在函数 insert 中),并且用 for,他应该问姓名、姓氏、年龄。

插入后,他应该打印,但为了快速,我会尝试使用数组(结构)的第一个元素(索引)。

【问题讨论】:

  • C 没有引用或传递引用。所有函数参数都按值传递,并且只能返回值。但是,您可以传递指针(按值)或返回指针,这具有类似的效果。

标签: c arrays struct reference


【解决方案1】:

您不能从函数返回整个数组,但可以返回数组的基本位置。例如,您可以这样做:person *insert(int *sz);。但是我在您的代码中看到您将&amp;p&amp;num 变量传递到插入方法中,也许您想在该函数中修改它们,然后在您的main() 中对其进行操作。为此,我有以下建议:

  1. 将第 16 行 person p 更改为 person *p。由于 p 应该保存数组的基值。请记住,数组名称只不过是列表第一个元素的基地址。
  2. 将您的函数定义更改为接收person** 而不是person*。由于您要修改指针变量,因此您需要一个指向指针变量的指针。像这样改变它:` void insert(person **p, int *num)
  3. 使用后释放内存;在 main 末尾添加 free(p)

`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2016-09-29
    • 2014-03-12
    • 2022-10-20
    • 2010-12-06
    相关资源
    最近更新 更多