user187772
user187772

Reputation:

Array Manipulation in C++

Help me understand this piece of code -

After the first iteration the value of PlcCode becomes A1*. How come? Shouldn't it be A*?

   Code = "A1";
   char Wild = '*';
   TDataString PlcCode(Code);

   for (int i = (Code.Len() - 1); i >= 0; i--)
   {          
      PlcCode[i] = Wild;
   }

Upvotes: 0

Views: 328

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

Another possibility

  • TDataString is storing non-null terminated data, and has a templated operator= accepting byte arrays.

This way, you could think of the code as

   TDataString Code(3);
   Code[0] = 'A';
   Code[1] = '1';
   Code[2] = '\0';

   char Wild = '*';
   TDataString PlcCode(Code);

   for (int i = 2; i >= 0; i--)
   {              
      PlcCode[i] = Wild;
   }

Imagine the following implementation of TDataString

struct TDataString {
  typedef unsigned char TElement;

public:
  TDataString(std::size_t n):data(n) { }

  template<typename T, std::size_t N>
  TDataString(T const (&d)[N]):data(d, d+N) { }

  TElement &operator[](std::size_t i) {
    return data[i];
  }

  std::size_t Len() const { return data.size(); }

private:
  std::vector<TElement> data;
};

Using that class, we can assign "A1" to Code, and it will give it a length of 3, and then executing the loop's first iteration will get us to A1*.

Upvotes: 3

LiraNuna
LiraNuna

Reputation: 67232

I see two possible scenarios:

  • TDataString is overloading operator[ ] and uses index 1 as a start (most likely to simulate another language).
  • Code.Len() does not give you the predictable output.

Of course, those are speculations, since I don't have any other information.

Upvotes: 3

Related Questions