While studying pointers I found that if I allocate memory for a 2 digit int I can give that int a higher value. Can someone explain me why it works like that and how to work around it?
Here is the code:
p = (int *) malloc(2*sizeof(int));
p = 123456;
That said, here, you're just overwriting the pointer returned by
malloc(). Don't do that. It will cause memory leak. Also, if you try to dereference this pointer later, you may face undefined behavior, as there is no guarantee that this pointer points to a valid memory location. Accessing invalid memory leads to UB.
Finally, to address
I allocate memory for a 2 digit int [...]
let me tell you, you are allocating memory to hold two integers, not a two digit integer. Also, to store the integer values into the memory area pointed by the pointer, you need to dereference the pointer, like
*p and store (assign) the value there, like
malloc() allocates memory of the size of bytes passed as it's argument. Check the
2*sizeof(int), if you want) to make it more clear.
Regarding this, quoting
void *malloc(size_t size);
mallocfunction allocates space for an object whose size is specified by
malloc() returns a pointer with the size of two integers (i.e., capable of holding two integer values), not two digits or bytes.