Thread: is there a function like sizeof that can be used at run time not compile time?

  1. #1
    Registered User
    Join Date
    Mar 2012

    is there a function like sizeof that can be used at run time not compile time?

    I am trying to make a program that reads several (lets say eight) bytes from a file into an array but what if there is only a few bytes left (lets say three)?
    Is an array the best option for doing this and if so how do I do a sizeof to determine how many bytes are left in the file.
    I am using C not C++ but is there a way to do it in either language and which one should I be using? I don't like OOP.
    I will be reading from the file into long long int or hex.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    First of all, sizeof is an operator, not a function.
    And no, there is no way to determine the 'size' of a bit of data.

    You need something like this
    struct fileRecord {
        int numValidBytes;
        unsigned char data[8];
    You fread() a max of 8 bytes into, and you use the return result of fread() to update rec.numValidBytes

    This you then pass around to whoever needs to know.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2010
    You have to store the number of bytes in a separate (unsigned integer) variable. Neither C nor C++ have run-time sizeof.
    If you have a buffer which can be of a fixed size, you can use a static array. If you need a variable-length block of memory, use malloc or variable-length array (C99 only).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Optimizing out virtual function calls at compile-time
    By golfinguy4 in forum C++ Programming
    Replies: 6
    Last Post: 01-26-2012, 01:35 AM
  2. Getting compile time.
    By ThatDudeMan in forum C Programming
    Replies: 2
    Last Post: 10-13-2010, 12:15 PM
  3. Using sizeof( long ) at compile time?
    By cpjust in forum C Programming
    Replies: 16
    Last Post: 11-14-2007, 01:22 PM
  4. Compile-Time Help
    By brayden37 in forum C++ Programming
    Replies: 0
    Last Post: 10-11-2001, 03:10 PM