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;
}
Another possibility
TDataString
is storing non-null terminated data, and has a templatedoperator=
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*
.
I see two possible scenarios:
TDataString
is overloadingoperator[ ]
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.
精彩评论