sizeof in C & C++

This is an interesting post.

#include <stdio.h>
#include <string.h>

#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)

int main()
{
    char arr[] = "shirley";
    printf("arr %s sizeof(arr) %ld strlen %ld \n", arr, sizeof(arr), strlen(arr));
    
    char arr2[10];
    printf("arr2 %s sizeof(arr) %ld strlen %ld \n", arr2, sizeof(arr2), strlen(arr2));
        
    char arr3[10] = "Shirley";
    printf("arr3 %s sizeof(arr) %ld strlen %ld \n", arr3, sizeof(arr3), strlen(arr3));
    
    /* The below line throws a warning 
       warning: initializer-string for array of chars is too long 
       */
    char arr4[4] = "Shirley";
    printf("arr4 %s sizeof(arr) %ld strlen %ld \n", arr4, sizeof(arr4), strlen(arr4));
    
    char arr5[7] = "Shirley";
    printf("arr5 %s sizeof(arr) %ld strlen %ld \n", arr5, sizeof(arr5), strlen(arr5));
    
    char arr6[] = "Shirley";
    printf("arr6 %s sizeof(arr) %ld strlen %ld \n", arr6, my_sizeof(arr6), strlen(arr6));
    printf("&arr6+1 %x &arr6 %x\n", (char *)(&arr6+1), (char *)(&arr6));
 
    return 0;
}

Output:

1
2
3
4
5
6
7
arr shirley sizeof(arr) 8 strlen 7 
arr2 ��o���o�Rn�(�o��shirley sizeof(arr) 10 strlen 25 
arr3 Shirley sizeof(arr) 10 strlen 7 
arr4 Shir sizeof(arr) 4 strlen 4 
arr5 ShirleyShir sizeof(arr) 7 strlen 11 
arr6 Shirley sizeof(arr) 8 strlen 7 
&arr6+1 ffc97d81 &arr6 ffc97d79


Click here to debug.


int a[] = {1,2,3,4,5};

sizeof(a) is 20 

sizeof (*a) is 4

 int size = sizeof(a)/sizeof(*a);


Difference between Char * and Int *?

Char* is a pointer to a character while int* is a pointer to an integer.Both will occupy same memory as that occupy by an integer but the differencebetween them occurs at the time of dereferencing.

// Type your code here, or load an example.
#include <stdio.h>

// On a 64 bit system
int main()
{
int *var = 0;
char *c = 0;

printf("var %d c %d\n", sizeof(var), sizeof(c));
printf("var %d c %d\n", sizeof(*var), sizeof(*c));

return 0;
}

Output:

1
2
3
var 8 c 8 
var 4 c 1
Click here to debug the above program.


References

https://stackoverflow.com/questions/32672693/calculating-pi-with-taylor-method-c

Comments