I am working on a project and are having some trouble with a part of my code.
I am copying data from a char array (dataArray) into a 2D char array (measurementArray), but when I clear or change the data in dataArray, the data in measurementArray is also changed. I believe the problem is that the pointer in measurementArray is simply pointing to the same data as dataArray holds, but I can't seem to fix it myself.
// This was my first attempt, which had the problem above
measurementArray[noOfReadings] = dataArray;
// This was my first attempt, which had the problem above.
measurementArray[noOfReadings] = dataArray;
// My second attempt - transferring the characters one by one.
// But when printing measurementArray, I got odd characters, such as this: "ð".
for(int j = 0; j < 11; j++) {
measurementArray[noOfReadings][j] = dataArray[j];
}
// Clearing dataArray to ensure no leftover data for when I put in new data.
if(dataArray[0] != 0x00) {
for(int j = 0; j < 11; j++){
dataArray[j] = 0x00, BYTE;
}
}
I should also mention that dataArray can hold between 3 and 11 characters. The tests I've done so far has usually been with 5 chars.
I think that is the interesting parts. Let me know if you need anything else.
The measurementArray item is an array of pointers. The dataArray is an array of chars. They are not the same thing. I'd remove the * in the measurementArray declaration. Then, the copy one character at a time method will work.
You could also use memcpy to copy the whole array at once.
Print 1 should be what I copied from dataArray to measurementArray[noOfReadings] - it is.
Print 2 is correct as well as it is displaying memory that haven't been used yet.
Print 3 however looks very strange to me. I just set it equal to "#####", but it displays the same data print 1.
Print 4 looks ok too.
Am I doing something wrong? This looks completely weird to me.
When the pointer is defined it can be pointed to a constant string. It can not be re-assigned to another constant string, though. I should have written that code snippet as:
I suppose so, but I'm only working on strings (char array).
My array is sent measurements wirelessly and holds them temporarily until they can be transferred (again wirelessly) to the computer.