【问题标题】:Is it possible to modify the content of a struct pointer inside a function?是否可以修改函数内部结构指针的内容?
【发布时间】:2022-01-07 13:19:04
【问题描述】:

我是 C 初学者,我试图创建一个修改结构指针内容的函数,但它无法实现,而是内容保持不变。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int age;
  int code;
}person;

void enter(person *struct_pointer);

void main(void)
{
  person *person_1 = NULL;

  enter(person_1);
  printf("CODE: %i\n", person_1->code);
  free(person_1);
}

void enter(person *struct_pointer)
{
 struct_pointer = malloc(sizeof(*struct_pointer));
 struct_pointer->age = 10;
 struct_pointer->code = 5090;
}

在上面的示例中,当我打印 person_1 的代码时,它什么也不打印,所以我假设是因为 person_1 仍然指向 NULL。

有人可以解释一下我该怎么做,如果不能做到,为什么。

谢谢

【问题讨论】:

    标签: c pointers struct pass-by-reference function-declaration


    【解决方案1】:

    要更改函数中的对象(指针是对象),您需要通过引用将其传递给函数。

    在 C 中,通过引用传递意味着通过指向对象的指针间接传递对象。因此,解引用该函数的指针可以直接访问原始对象。

    所以你的函数应该按以下方式声明和定义

    void enter(person **struct_pointer)
    {
        *struct_pointer = malloc(sizeof(**struct_pointer));
        if ( *struct_pointer )
        {
            ( *struct_pointer )->age = 10;
            ( *struct_pointer )->code = 5090;
        }
    }
    

    并像这样称呼

    enter( &person_1 );
    

    否则在此函数声明的情况下

    void enter(person *struct_pointer);
    

    该函数将处理传递的指针值的副本,并且在函数内更改副本不会影响原始指针。

    注意,根据C标准,没有参数的函数main应该声明为

    int main( void )
    

    【讨论】:

    • 不需要使用双指针,除非他们想修改指针指向的位置。在这种情况下,只要预先分配了数据,单个指针就会更简单并且工作得一样好。
    【解决方案2】:

    您可以修改结构的内容。它对您不起作用,因为您是在 enter 函数中创建一个新结构,而不是编辑原始结构。只需删除第一行(带有malloc 的行),然后在person_1variable 的声明中分配结构。

    【讨论】:

      猜你喜欢
      • 2013-11-13
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2020-08-21
      • 2015-08-22
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多