How to find out int size without sizeof

Possible duplicate:
data type size without using sizeof

This is a question asked in an interview with C, I wanted to know what is the right logic for this

If you don't have a sizeof operator in C, how do you know the size of an int?

+3
source share
4 answers

Use the array [*]:

int a[2];
int sizeof_int = (char*)(a+1) - (char*)(a);

Actually, because of the note in the section on pointer arithmetic, you do not even need an array, because for the purpose of pointer arithmetic, an object behaves like an array of size 1 and the pointer outside the end is legal for the array:

int a;
int sizeof_int = (char*)((&a)+1) - (char*)(&a);

[*] By this I mean that "solving a puzzle is using an array." Do not actually use an array, use sizeof!

+10

- int.

0

I think of two ways. One of them is to print “-1” as an unsigned value and output the size based on the printed number. Secondly, these are:

#include <stdio.h>

int size()
{
  int a = 1;
  int size = 1;
  while(a<<=1)
    size++;
  return size;
}

int main(int argc, char** argv)
{
  printf("Size of int: %d\n", size());
  return 0;  
} 
0
source

Declare int, initialize it to -1. Repeats "<1" to 0. Number of offsets specified = size in bits. '<<3' for size in bytes.

Rgds, Martin

0
source

All Articles