Write a C program to find the size of given data type without using sizeof operator.
#include <stdio.h>
int main() {
int size, ch;
printf("Find the size of:\n");
printf("1. Integer\t2. Character\n");
printf("3. Float\t4. Double\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch(ch) {
case 1:
/* adding 1 to integer pointer gives int size */
size = (int) (1 + (int *)0x0);
printf("Size of Integer: %d\n", size);
break;
case 2:
/* adding 1 to char pointer gives size of char */
size = (int) (1 + (char *)0x0);
printf("Size of Character: %d\n", size);
break;
case 3:
/* adding 1 to float ptr gives size of float */
size = (int) (1 + (float *)0x0);
printf("Size of Float: %d\n", size);
break;
case 4:
/* adding 1 to double pointer gives size of double */
size = (int) (1 + (double *)0x0);
printf("Size of Double: %d\n", size);
break;
default:
printf("Wrong Option!!\n");
break;
}
return 0;
}
int main() {
int size, ch;
printf("Find the size of:\n");
printf("1. Integer\t2. Character\n");
printf("3. Float\t4. Double\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch(ch) {
case 1:
/* adding 1 to integer pointer gives int size */
size = (int) (1 + (int *)0x0);
printf("Size of Integer: %d\n", size);
break;
case 2:
/* adding 1 to char pointer gives size of char */
size = (int) (1 + (char *)0x0);
printf("Size of Character: %d\n", size);
break;
case 3:
/* adding 1 to float ptr gives size of float */
size = (int) (1 + (float *)0x0);
printf("Size of Float: %d\n", size);
break;
case 4:
/* adding 1 to double pointer gives size of double */
size = (int) (1 + (double *)0x0);
printf("Size of Double: %d\n", size);
break;
default:
printf("Wrong Option!!\n");
break;
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:1
Size of Integer: 4
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:2
Size of Character: 1
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:3
Size of Float: 4
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:4
Size of Double: 8
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:1
Size of Integer: 4
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:2
Size of Character: 1
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:3
Size of Float: 4
jp@jp-VirtualBox:~/$ ./a.out
Find the size of:
1. Integer 2. Character
3. Float 4. Double
Enter your choice:4
Size of Double: 8
No comments:
Post a Comment