Is the size of C “int” 2 bytes or 4 bytes?

后端 未结 13 2515
不知归路
不知归路 2020-11-22 10:52

Does an Integer variable in C occupy 2 bytes or 4 bytes? What are the factors that it depends on?

Most of the textbooks say integer variables occupy 2 bytes. But whe

13条回答
  •  忘了有多久
    2020-11-22 11:12

    This is a good source for answering this question.

    But this question is a kind of a always truth answere "Yes. Both."

    It depends on your architecture. If you're going to work on a 16-bit machine or less, it can't be 4 byte (=32 bit). If you're working on a 32-bit or better machine, its length is 32-bit.

    To figure out, get you program ready to output something readable and use the "sizeof" function. That returns the size in bytes of your declared datatype. But be carfull using this with arrays.

    If you're declaring int t[12]; it will return 12*4 byte. To get the length of this array, just use sizeof(t)/sizeof(t[0]). If you are going to build up a function, that should calculate the size of a send array, remember that if

    typedef int array[12];
    int function(array t){
        int size_of_t = sizeof(t)/sizeof(t[0]);
        return size_of_t;
    }
    void main(){
        array t = {1,1,1};  //remember: t= [1,1,1,0,...,0]
        int a = function(t);    //remember: sending t is just a pointer and equal to int* t
       print(a);   // output will be 1, since t will be interpreted as an int itselve. 
    }
    

    So this won't even return something different. If you define an array and try to get the length afterwards, use sizeof. If you send an array to a function, remember the send value is just a pointer on the first element. But in case one, you always knows, what size your array has. Case two can be figured out by defining two functions and miss some performance. Define function(array t) and define function2(array t, int size_of_t). Call "function(t)" measure the length by some copy-work and send the result to function2, where you can do whatever you want on variable array-sizes.

提交回复
热议问题