Why there is difference in the output between the C code and the Arduino IDE ? The output of this c code =16
typedef struct str
{
int* array;
int y;
int z;
} str;
void neww() {
printf("str=%d\n",sizeof(str)); //
}
void main(){
neww();
}
And when run it on esp32 I get on output =12 !!! why?! This is the code of Arduino IDE
typedef struct str
{
int* array;
int y;
int z;
} str;
void neww() {
printf("str=%d\n",sizeof(str)); //
}
void setup(){
Serial.begin(115200);
delay(500);
neww();
}
void loop(){}
CodePudding user response:
I will simplify your problem:
In your computer:
int *int_pointer;
printf("Size of int_pointer: %d", sizeof(int_pointer)); // Output: 8
In your ESP32:
int *int_pointer;
printf("Size of int_pointer: %d\n", sizeof(int_pointer)); // Output: 4
That is the difference.
A pointer stores a memory address so its size will be (at least) the same as the size of an address in its respective processor.
- Your computer is a 64-bit system -> The size of each address is 8 bytes -> The pointer needs to have 8 bytes to be able to store it.
- Your ESP32 is a 32-bit system -> The size of each address is 4 bytes -> The pointer only needs to have 4 bytes to be able to store it.
CodePudding user response:
This stuct
typedef struct str
{
int* array;
int y;
int z;
} str;
contains a pointer (int * array). The size of pointers depends on where the code is running. On a 32 bit machine they will be 4 bytes, on a 64 bit machine 8. There can be other sizes to (2 - pdp 11, 6 - some mainframes)
So the sizeof operator will return different values on different systems