Using 'dummy' pointers for comparison

I have a structure that contains a string (pointer to character).

This string / array must be in the form of one of the following:

  • contain actual string data
  • no actual data, just needs to be able to show it in STATE_1

  • same as above, but STATE_2

I want to check if a string is in STATE_1

or STATE_2

, and do something differently than if it contained actual data. If I only had one state, I could use a null pointer.

I've tried something along these lines, but it leads to undefined behavior.

char *STATE_1, *STATE_2;
...
if(tstruct.string == STATE_1 || tstruct.string == STATE_2){
    ...
}

      

+3


source to share


3 answers


Reserve two static addresses. They are guaranteed to be unique.

static char STATE_1[1];
static char STATE_2[1];

if (tstruct.string == STATE_1 || tstruct.string == STATE_2) {
    ...
}

      



These can be global variables, or they can be static locales, or one.

+4


source


I'm not sure, but I think you want something like this:



char STATE_1, STATE_2; // dummy 'char for 2. and 3.

if (tstruct.string == &STATE_1 || tstruct.string == &STATE_2) {
   // ...
}

      

+2


source


There are several ways to do this:

1) You can have a variable in a structure that is of type enum stringState, which can be 0.1 or 2 (0 means String has data, 1 means State-1 and 2 means State-2). The downside is that you have to change stringState every time you change data, and there will be consequences if you forget to do this.

2) The line itself can be "STATE1" or "STATE2" and you can then execute strcmp with "STATE1" or "STATE2" otherwise they will have actual data (STATE0).

0


source







All Articles