-4

In C I wish to create a data type (like int or float) that has only 1byte. How can I possible do this? I've tried with malloc() but didn't work that way I tried.

Could you please give me a hand here?

Example:

sizeof(int) = 4 bytes
sizeof(char) = 1 byte
sizeof(float) = 4 bytes
sizeof(myDataType) = 1 byte
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Telmo Vaz
  • 189
  • 1
  • 2
  • 11
  • 3
    What did you try? There aren't many ways to do it, but it can be done. – Jonathan Leffler Oct 11 '13 at 13:09
  • 2
    What do you mean with "create a datatype"? Allocate storage space? Declare some type, which takes exactly one byte? – Dirk Oct 11 '13 at 13:09
  • Aren't you searching for the type "char" (1byte) ? – Joze Oct 11 '13 at 13:10
  • CHECK THIS : http://stackoverflow.com/questions/14536736/typedef-a-bitfield-variable – Jonysuise Oct 11 '13 at 13:12
  • 1
    @TelmoVaz: You already have a standard data type of size 1 byte: [`uint8_t`](http://en.cppreference.com/w/c/types/integer). Use this happily intead of mallocing and forgetting to free it later on. – legends2k Oct 11 '13 at 13:13
  • 1
    @legends2k The standard 1-byte type is `char`. Nothing guarantees that `uint8_t` takes up one byte. –  Oct 11 '13 at 13:49
  • @H2CO3: Then what's the point of [u]intN_t types? The only value they add is giving a guarentee on the signedness and length. – legends2k Oct 11 '13 at 14:03
  • @legends2k They guarantee exact (or minimal, for `*min_t` types) **bit** width. Don't confuse bytes with octets. –  Oct 11 '13 at 14:05
  • I actually want to use 1byte type for integer. I wish to use it to options in switches and number menu options. And I would like to create my own data type to use it, without having to include any libraries besides stdio and stdlib – Telmo Vaz Oct 12 '13 at 01:08

1 Answers1

4

There is such data type. char is always guaranteed to be one byte long. If you want another name for that type, just use typedef and create a new type based on char.

More detailed explanation can be found in this question: Are there machines, where sizeof(char) != 1, or at least CHAR_BIT > 8?

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114