【问题标题】:how to initialize struct array members inside function by reference如何通过引用初始化函数内部的结构数组成员
【发布时间】:2021-10-13 22:43:39
【问题描述】:

我试图创建一个结构数组并初始化结构数组成员,但我不知道如何访问结构成员,我使用了(st->ch)[t] = 'c'; 和其他类似的语法但我没有成功。

最好的问候。

struct ST
{
    char ch;
};

bool init(ST* st, int num)
{
    st = (ST*)malloc(num * sizeof(ST));
    if (st == NULL) return false;

    for (int t = 0; t < num; t++) (st->ch)[t] = 'c';

    return true;
}

int main()
{
    ST* s = NULL;
    init(s, 2);

    putchar(s[1].ch);
}

【问题讨论】:

标签: c struct pass-by-reference dynamic-memory-allocation member-access


【解决方案1】:

你在 main 中声明了一个指针

ST* s = NULL;

在 C 中应该被声明为

struct ST* s = NULL;

因为您声明了类型说明符 struct ST(在 C 中与 ST 不同)

struct ST
{
    char ch;
};

您将在函数中进行更改。为此,您必须通过引用将指针传递给函数。那就是函数声明至少看起来像

bool init( struct ST **st, int num );

函数的调用方式如下

init( &s, 2);

if ( s ) putchar( s[1].ch );

函数本身可以这样定义

bool init( struct ST **st, int num )
{
    *st = malloc( num * sizeof( struct ST ) );

    if ( *st )
    {
        for ( int i = 0; i < num; i++) ( *st )[i].ch = 'c';
    }

    return *st != NULL;
}

如果您使用的是 C++ 编译器,请替换此语句

    *st = malloc( num * sizeof( struct ST ) );

    *st = ( struct ST * )malloc( num * sizeof( struct ST ) );

当不需要结构数组时,您应该释放数组占用的内存,例如

free( s );

【讨论】:

    【解决方案2】:

    您可以使用以下方式访问结构成员:

    st[t].ch
    

    【讨论】:

    • 我之前测试过,它不起作用,而且它也是我们必须使用的指针 -> 而不是。
    • @Sofia “不起作用”从来都不是一个好的问题描述。你遇到了什么具体的错误或问题?请参阅我上面的评论,了解为什么即使在修复之后代码仍然错误。
    • st[t].ch 不起作用?什么错误?
    • @kaylum 好的,谢谢,我会检查链接
    • @Sofia [t] 不需要 -&gt;,因为它已经取消引用指针。
    【解决方案3】:

    正如@kaylum 所提到的stinit() 中的一个局部变量,并且不会在主函数中更新变量s,因此另一种选择是您可以通过添加变量@ 的地址987654324@ 到 init() 或者可以只返回分配的内存,如下面的代码 sn-p 所示。除了使用bool 作为返回类型来检查你可以使用ST* 作为返回类型,如果它返回NULL 或mem 地址来获取mem alloc 状态。

    您还必须对结构 typedef struct ST ST; 进行 typedef 才能直接将类型用作 ST 否则您将不得不坚持使用 struct ST

    typedef struct ST
    {
        char ch;
    }ST;
    
    ST* init(int num)
    {
      ST *st;
    
      // Create num elems of ST type
      st = (ST*)malloc(num * sizeof(ST));
    
      // return NULL is st unintialised
      if (st == NULL) {
        return st;
      }
    
      // Assign ch member variable of the 't'th st element wit 'c'
      for (int t = 0; t < num; t++) {
        st[t].ch = 'c';
      }
    
      return st;
    }
    
    int main()
    {
      ST* s;
    
      // creates an array of size two of type st
      s = init(2);
    
      putchar(s[1].ch);
    
      return 0;
    }
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2017-06-23
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多