0

Using ArduinoJson I have assigned a value such as;

const char* id = root["id"];

in the original JSON id was "1"

if (strcmp(id, "1") == 0) {
    // this executes
}

I have an array of structs that I wish to compare the id against. The struct looks like;

typedef struct  {
   char id[2];
   ....
} Device;

I assign an id (1-9) into the struct id by

_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

where _cmd is of type Device. Devices is an array with up to 8 entries Now I try to find a match in the devices using the JSON id

for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

I can't seem to get a match I have also tried (Devices[i].id == id)

  • 1
    Strcmp is the way to go, but I'm not sure your code is giving away what the issue is, Mikaels answer is a more explicit version of what I imagine your code looks like. I presume you initialize DevicesPtr to 0 at some point? Mikael is also renaming your variables to more useful names another good idea : Could you post the code in full? – Caribou Dec 23 '15 at 14:23
1

Try something like this:

typedef struct  {
  char id[2];
  ....
} Device;

const int DEVICES_MAX = 8;
Device Devices[DEVICES_MAX];

for (int i = 0; i < DEVICES_MAX; i++) {
  Devices[i].id[0] = '1' + i;
  Devices[i].id[1] = 0;
  ...
}

for (int i = 0; i < DEVICES_MAX; i++) {
  if (!strcmp(Devices[i].id, id)) {
  ...
}

Cheers!

| improve this answer | |
1

You can't compare a char and a string.. How can you compare apples and bananas?

Now, you have two ways to do your job.

1) do as @Mikael Patel suggests, so convert your ids into strings. This is fine because it will allow you to deal with multiple chars ids.

2) a more efficient way to do this (note that this works with just SINGLE CHARS IDS) is the following one:

if (strlen(id) == 1) {
    for (byte i = 0; i < DevicesPtr; i++) {
        if (Devices[i].id == id[0]) {
           // This code will execute if ids match
        }
    }
}

Note that id should be exactly 1 char long, otherwise the whole comparison as you thought is meaningless

With this solution you don't need multibyte id char in the struct definition, so you can just define

typedef struct  {
   char id;
   ....
} Device;

and, in the code,

_cmd.id = '0' + (++DevicesPtr);
Devices[DevicesPtr-1] = _cmd;
| improve this answer | |
  • 1
    Actually this can be improved further. The id field in the struct is not needed as the index is a function of the value (i.e. index = id - '1'). The test is simply that the index must be in [0..last_device] and last_device in [0..MAX_DEVICES-1]. A search is not really required if the id is ['1'...'9']. – Mikael Patel Dec 23 '15 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.