返回结构的数组或结构指针数组? [英] return an array of structs or an array of struct pointers?

查看:165
本文介绍了返回结构的数组或结构指针数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你需要返回一个结构从一个函数,你通常会返回一个指针结构代替

如果你再想返回结构的数组,它是建议:


  1. 返回结构的阵列(指针的第一个元素)

  2. 或返回结构指针数组?

我画的图下面的两个选项:

1

2

由于以下结构定义

 结构值{
    int类型的;
    INT B:
};

下面是一些示例code从两个选项访问结构的字段:

选项#1:

 结构值*丘壑= get_values​​1();
 的printf(%D,%d个\\ N,数值[0] .A,值[1] .B);

选项#2:

 结构值**丘壑= get_values​​2();
 的printf(%D,%d个\\ N,数值[0] - >一种,值[1] - > B);


解决方案

我看不使用版本1的唯一问题是,它可能会更容易在第二个版本,以确定结构(返回)的数量,作为指针可以用作止动元件,而在第一个版本,它可能无法以限定的止动元件。

If you need to return a struct from a function, you would normally return a pointer to the struct instead.

If you then want to return an array of structs, is it recommended to:

  1. return an array of structures (pointer to the first element)
  2. or return an array of struct pointers?

I have drawn a diagram for the two options below:

1:

2:

Given the following struct definition

struct values {
    int a;
    int b;
};

here is some sample code for accessing the fields of the structs from the two options:

Option #1:

 struct values *vals = get_values1();
 printf("%d, %d\n", values[0].a, values[1].b);

Option #2:

 struct values **vals = get_values2();
 printf("%d, %d\n", values[0]->a, values[1]->b);

解决方案

The only issue I see to not use version 1, is that it might be easier to identify the number of structures (returned) in the second version, as a NULL pointer can be used as a stopper element, whereas in the first version it might not be possible to define a stopper element.

这篇关于返回结构的数组或结构指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆