Hi everyone, i want to create a dynamic array using malloc and realloc functions, but i just can't understand how they work. I wrote some code to figure it out, and after seeing how this little program worked, i have some doubts.
Here's the code:
This program shows in the screen the following string:Code:int main(int argc, char *argv[]) { int *myarray; myarray = malloc ( sizeof ( int ) * 3 ); myarray[0] = 20; myarray[1] = 21; myarray[2] = 22; int i; for ( i = 0 ; i < 3 ; i++ ) { printf ( "%i\n" , myarray[i] ); } myarray= realloc ( myarray , sizeof ( int ) * 1 ); myarray[5] = 25; printf ( "%i\n" , myarray[5] ); system("PAUSE"); return 0; }
20
21
22
25
wich is not ok. There are things in the code that i just don't get it. When i use malloc function, i'm declaring that myarray will have only three elements. Then i assign a value for each of these. After that, i show them in the screen, doing a loop. Then, with realloc function i determine that now myarray will have only one element. But, why C compiler just let me to assign a value to an element wich is supposed to not exist?. It's not supposed to erase all elements except the first?. Even if i didn't call realloc function, and added a new element to myarray wich its index was greater than two (remember that i apparently declared an array with three elements), c compiler would let me assign a value for it too. Doesn't malloc reserve a contiguous space of memory specified in bytes by its param?, if it does, why i can simply add an arbitrary number of elements, occupying all memory i want, without limits, without errors and without exceptions?.
I hope you can help me on this guys.
Thanks in advance.
Regards.



LinkBack URL
About LinkBacks



