Search code examples
stringassociative-arraycapl

CAPL associative array with string types


Following this paper, I'm trying to create an associative array like this:

variables
{
  char[30] translate[ char[] ];
} 

It is exactly the same example in the paper. Problem comes when I try to put values to this associative array. For example:

on preStart
{
  translate["hello"] = "hola";
}

That gives me a compilation error: "Error 1112 at (89,23): operand types are incompatible"

What I'm doing wrong?

VERSIONS: I'm using Vector CAPL Browser included with CANalyzer version 11.0 SP2


Solution

  • With associative fields (so-called maps) you can perform a 1:1 assignment of values to other values without using excessive memory. The elements of an associative field are key value pairs, whereby there is fast access to a value via a key.

    An associative field is declared in a similar way to a normal field but the data type of the key is written in square brackets:

    int m[float];         // maps floats to ints
    float x[int64];       // maps int64s to floats
    char[30] s[ char[] ]  // maps strings (of unspecified length) to strings of length < 30
    

    If the key type char[] is specified, all the character fields (of any size) can be used as key values. In the iteration the loop variable must then also be declared as char[]. Key comparisons, e.g. in order to determine iteration sequence, are then performed as character string comparisons, whereby no country-specific algorithms are used.

    char[] is the only field type that can be used as a key type. Please bear in mind that you can not declare variables or parameters of the char[] type, with the exception of loop variables in the iteration.

    Association between strings:

    char[30] namen[char []];
    strncpy(namen["Max"], "Mustermann", 30); 
    strncpy(namen["Vector"], "Informatik", 30);
    
    for (char[] mykey : namen)
    {
      write("%s is mapped to %s", mykey, namen[mykey]);
    }