-2

私は非常に奇妙な問題に遭遇しました。構造体を定義し、それを const ポインターとして関数に渡しました。コードは以下のようなものです。

typedef struct a{
  char str1[256];
  ...
  int x;
}a_t;

int f(..., const a_t *a){...}

a_t a;
...
a.x = 1;
f(..., &a);
...

問題は、f() に入ると、常に 0 である変数 a->x を出力することです!?? しかし、構造体メンバー x を構造体の先頭 (他のメンバーの前) に移動すると、1 になります。これは正しいです。

パラメータとして構造体ポインタを使用するためのトリックやトラップはありますか?

[EDIT1] 関数 f() の 1 行目で printf が呼び出されます

4

1 に答える 1

2

Cannot comment so I will suggest debugging option. Can you please add print of the struct element x address in the function and before. If it is the same someone is changing it, otherwise we are not looking at the same value.

typedef struct a{
  char str1[256];
  ...
  int x;
}a_t;

int f(..., const a_t *a)
{
    printf("X value %d, address %p", a->x, &(a->x));
    ...
}


a_t a;
...
a.x = 1;
printf("X value %d, address %p", a.x, &(a.x));
f(..., &a);
...

Also detail view of the function could help

于 2012-08-11T09:56:38.753 に答える