-3

I have a pointer to a struct that contains a pointer to a short value. The following is the struct.

typedef struct {
  short *val;
} x;

If I have a pointer to a variable of type x, I can dereference it and access an element of the struct by doing x->val, but since val is a pointer as well, this only gives me the adress of val. How can I dereference this to access the value of val? I tried *(x->val), but that is not working. Or should it work like this, and my mistake has to be something entirely different?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ralph
  • 37
  • 6
  • 1
    `*(x->val)` should work, assuming you've initialized the pointer to point to something. – Barmar Apr 25 '22 at 20:03
  • 2
    The struct type is `x`. Do you also have a variable `x *x`? Please create a [mre]. – 001 Apr 25 '22 at 20:04
  • assuming your `x` is really of type `x`, which itself is odd, *"this only gives me the address of val"* - that is not accurate, and in pointer/dereference land, details *really* matter. It gives you the address *held by `val`*, not the address *of* `val`. Anyway, you dereference the way you would any other non-void pointer. – WhozCraig Apr 25 '22 at 20:05

1 Answers1

3

It seems you are using the structure name in this expression

*(x->val)

Instead you need to use a pointer to an object of the structure type. For example

#include <stdio.h>

typedef struct {
  short *val;
} x;

int main( void )
{
    short value = 10;
    x obj = { .val = &value };
    x *p = &obj;

    printf( "%d\n", *p->val );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335