0

I have a simple sketch as shown below:

class Simple {
public:
    byte* Data;
};

Simple simple;
byte data[3] { 0x41, 0x42, 0x43 };

void setup() {
    simple.Data = data;
    Serial.begin(9600);
}

void loop() {
    Serial.print("sizeof(data): ");
    Serial.println(sizeof(data));
    Serial.print("sizeof(simple.Data): ");
    Serial.println(sizeof(simple.Data));
    for(int i = 0; i < sizeof(data); i++) 
    { 
        Serial.print(data[i]); Serial.print(' '); 
    }
    Serial.println();
    for(int i = 0; i < sizeof(simple.Data); i++) 
    { 
        Serial.print(simple.Data[i]); Serial.print(' '); 
    }
    Serial.println();
    for(int i = 0; i < sizeof(data); i++) 
    { 
        Serial.print(simple.Data[i]); Serial.print(' '); 
    }
    Serial.println();
    delay(1000);
}

Here is the output:

sizeof(data): 3
sizeof(simple.Data): 2
65 66 67 
65 66 
65 66 67 

When I check the size of the array (sizeof(data)) and compare it to the size of the Data member of the class instance (sizeof(simple.Data)), they don't match. When I dump the contents of both arrays, they each have three elements.

I'm new to C/C++ (coming from a C# background) so my grasp of pointers et al is weak. Am I missing something here?

Thanx

mikyra
  • 10,077
  • 1
  • 40
  • 41
user1325543
  • 523
  • 3
  • 12
  • 1
    [Arrays aren't pointers.](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – chris May 03 '15 at 00:28
  • 1
    The expression `sizeof(simple.Data)` returns the size of the *pointer* and not what it points to. – Some programmer dude May 03 '15 at 00:29
  • Why does the sizeof(data) and sizeof(simple.Data) return different values? Don't they both point to the size of the pointer in this case? That's confusing. Is the pointer to data 3 bytes where as the pointer to simple.Data is only 2? Why would that be the case? – user1325543 May 03 '15 at 00:38
  • Ok, I think maybe I'm starting to understand a little better. I changed the size of the data array to 'data[5]' and ran the code again. The output was consistent with your comment. So, what I need to know then is how many elements are in the array the pointer for simple.Data is pointing to? I.e., if I assign an array of arbitrary size to the Data member, all I have access to in code (in the Simple class) is the pointer reference. So, how can I determine the number of elements in the array? That's the essence of what I was trying to do when I ran into this issue. Thanx, – user1325543 May 03 '15 at 00:52
  • I think I get it now. The link from chris pointed me in the right question and helped my frame my google search better. for now, i – user1325543 May 03 '15 at 03:16
  • for now i'm just passing in an additional parameter to my method that species the length of the array the pointer is referencing. not elegant, but solves my immediate problem. thanx, – user1325543 May 03 '15 at 03:17

0 Answers0