C error: expression must have arithmetic or pointer type while accessing union member within structure

user1612078 Source

Getting error error: expression must have arithmetic or pointer type in following code snippet. Not sure whats going wrong.

struct structX
{
  union {
    structA varA; /* structA is a structure */
    structB varB; /* structB is a structure */
  } unionX;

#define xa unionX.varA
#define xb unionX.varB 
}

void foo(structX **sxpp) {
  structX *sxp = *sxpp;
  /* i want to do null check for xb */
  if (sxp-> xb) /* error: expression must have arithmetic or pointer type */
  {
     ...
  }
}

I tried to deference the pointer as well, something like this, but no success.

if ((**sxpp).xb)
c

Answers

answered 6 months ago achal #1

The problem in the below statement

structX *sxp = *sxpp;

It should be struct structX *sxp = *sxpp;

Or first typedef the structure as

typedef struct structX
{
  union {
    /* make sure below structure are typedefed above */
    structA varA; /* structA is a structure */
    structB varB; /* structB is a structure */
  } unionX;
}structX;

And then create the variable as

structX *sxp = *sxpp;

Modify the foo function accordingly

void foo(structX **sxpp) { ... } /* if typedefed */

or

void foo(struct structX **sxpp) { ... } /* if not typedefed

Edit : Since your question doesn't explain about structA and structB. lets say structB looks like

typedef struct struct_b {
        int y;
}structB;

the code block

if (sxp->xb) {
            ...
}

should be below one if you want to check whether member of structB is NULL or not

if (sxp->xb.y) { /* let say y is data member of structB */
       ...
}

answered 6 months ago squeamish ossifrage #2

In this statement:

if (sxp-> xb) { ... }

you are trying to evaluate a struct (sxp->unionX.varB) as either true or false. Your compiler is trying to tell you that this won't work. The expression inside an if() statement must either be an arithmetic value (e.g., if (i < 10), where i < 10 evaluates to 0 or 1), or a pointer (e.g., f = fopen("a.txt", "r"); if (f) { ... }).

You can't evaluate a struct in this way. Did you perhaps mean to check the value of an element of varB inside this union?

comments powered by Disqus