【问题标题】:How to access/modify variable inside struct with a pointer to struct?如何使用指向结构的指针访问/修改结构内的变量?
【发布时间】:2015-11-11 00:46:42
【问题描述】:

我有这个代码:

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

typedef struct vector_{
    int x;
    double y;
    double z;
} *vector;

void modi(vector a);

int main() {
  vector var;
  var->x = 2;
  modi(var);
  return 0;
}

void modi(vector a){
  printf("avant modif %d",a->x);
  a->x = 5;
  printf("avant modif %d",a->x);
}

我尝试运行它,但出现分段错误。

问题很简单:使用结构指针变量进行访问/修改。

我查看 Stack Overflow,但我的问题的答案不完整:https://stackoverflow.com/a/1544134

在这种情况下访问/修改的正确方法是什么(struct 指针变量)?

【问题讨论】:

  • vector var = malloc(sizeof(vector)); 如果你打算这样做,你必须分配空间......
  • 如果你不尝试在你的 typedef 后面隐藏间接性,你就不会迷惑自己了?
  • @Kevin vector var = malloc(sizeof(*var));
  • 你从来没有为指针分配任何空间;当您取消引用未初始化的指针时,您会调用未定义的行为。而且,一般来说,不要将指针隐藏在 typedef 后面。
  • @EOF 我看到隐藏间接比标准方式更安全。这就是我会使用它的原因。

标签: c pointers struct typedef


【解决方案1】:

请试试这个,它有效,我扩展了一点。请阅读代码中的cmets。

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

struct vector_
{
  int x;
  double y;
  double z;
};

typedef struct vector_ *vector;
void modi( vector a );

int main(  )
{
  struct vector_ av;    // we have a structure av
  vector var = &av;     // pointer var points to av
  var->x = 2;

  printf( "\ndans main() avant call to modi() %d", var->x );

  modi( var );

  printf( "\ndans main() apres call to modi() %d", var->x );
  return 0;
}

void modi( vector a )
{
  printf( "\ndans modi() avant modif %d", a->x );
  a->x = 5;
  printf( "\ndans modi() apres modif %d", a->x );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多