Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating integer variable of a defined size

Tags:

c++

c

I want to define an integer variable in C/C++ such that my integer can store 10 bytes of data or may be a x bytes of data as defined by me in the program. for now..! I tried the

int *ptr;
ptr = (int *)malloc(10);

code. Now if I'm finding the sizeof ptr, it is showing as 4 and not 10. Why?

like image 386
1s2a3n4j5e6e7v Avatar asked Aug 06 '26 21:08

1s2a3n4j5e6e7v


2 Answers

C and C++ compilers implement several sizes of integer (typically 1, 2, 4, and 8 bytes {8, 16, 32, and 64 bits}), but without some helper code to preform arithmetic operations you can't really make arbitrary sized integers.

The declarations you did:

int *ptr;
ptr = (int *)malloc(10);

Made what is probably a broken array of integers. Broken because unless you are on a system where (10 % sizeof(int) ) == 0) then you have extra bytes at the end which can't be used to store an entire integer.

There are several big number Class libraries you should be able to locate for C++ which do implement many of the operations you may want preform on your 10 byte (80 bit) integers. With C you would have to do operation as function calls because it lacks operator overloading.

Your sizeof(ptr) evaluated to 4 because you are using a machine that uses 4 byte pointers (a 32 bit system). sizeof tells you nothing about the size of the data that a pointer points to. The only place where this should get tricky is when you use sizeof on an array's name which is different from using it on a pointer. I mention this because arrays names and pointers share so many similarities.

like image 100
nategoose Avatar answered Aug 08 '26 11:08

nategoose


Because on you machine, size of a pointer is 4 byte. Please note that type of the variable ptr is int *. You cannot get complete allocated size by sizeof operator if you malloc or new the memory, because sizeof is a compile time operator, meaning that at compile time the value is evaluated.

like image 29
Donotalo Avatar answered Aug 08 '26 12:08

Donotalo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!