smokeyace
smokeyace

Reputation: 21

Why do all C++ array elements get set despite addressing just one item?

I have an array of structures for which I need to convert a CString into a char array. This conversion occurs for 1000 data points and the output is written into a new array. So my problem is: I have a for loop that iterates through the array of CStrings and converts them into a char array and writes that into my "new" array. The problem is that each iteration writes the newly converted char array to all previous array elements. E.g newArr[0] = oldArr[0] = working. newArr[1] = oldArr[1] BUT now newArr[0] also = oldArr[1]. Then newArr[2] = oldArr[2] but again newArr[0], newArr[1] and newArr[2] = oldArr[2].

My code is as follows:

    for (size_t i = 0; i < MAX_TAGS; i++)
{
    char nodeStr[40];
    strcpy_s(nodeStr, (strlen(theConf.confP[i].nodeID) + 1), theConf.confP[i].nodeID);
    monitoredNodes[i] = UA_NODEID_STRING(theConf.confP[i].namespaceIndex, nodeStr);
}

I guess I've done something wrong here but I've tried all sorts including looking at compiler optimisations but every time its the same problem, despite me setting an array item by index, all previous array items seem to get written too.

Upvotes: 0

Views: 79

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136505

You keep creating and destroying char nodeStr[40] buffer on each loop of iteration. That buffer gets created at the same stack address where the buffer from previous iteration resided, this is why it looks like you overwrite the previous values. You probably want that buffer to persist rather than be overwritten.

You probably do not need to copy the string, just pass use its internal zero-terminated buffer:

for(size_t i = 0; i < MAX_TAGS; ++i) {
    char const* nodeStr = theConf.confP[i].nodeID.GetBuffer();
    monitoredNodes[i] = UA_NODEID_STRING(theConf.confP[i].namespaceIndex, nodeStr);
}

If UA_NODEID_STRING creates/formats a new string, it is best for it to return a CString or std::string by value and make monitoredNodes an array of those, e.g. CString monitoredNodes[MAX_TAGS];.

Upvotes: 2

Related Questions