Concept

How do you use and validate a dynamically allocated array?

ComputerScienceOne / Dynamic Memory

"Once created, a dynamic array can be used just like a static array. You use the array’s identifier as well as an index to access or modify each element. The same rules and pitfalls apply, so care must be taken to not access elements outside the bounds of the array.\n\nFinally, when using malloc() it is important to understand that the memory that is allocated is uninitialized. Just as with variables you cannot make any assumptions as to the contents of the memory space that is allocated. It may contain garbage values, it may contain the contents that occupied the memory last time it was used, etc.\n\nA full example:\n\nint n = 100;\n\nint *arr = NULL;\n\narr = (int *) malloc(sizeof(int) * n);\n\nif(arr == NULL) {\n\nfprintf(stderr, \"unable to allocate memory!\n\n\");\n\nexit(1);\n\n}\n\nfor(i=0; i<n; i++) {\n\narr[i] = (i+1) * 10;\n\nprintf(\"a[%d] = %d\n\n\", i, arr[i]);\n\n}"

Related Ideas

How do you use and validate a dynamically allocated array? | ComputerScienceOne | Bifalgorithm | Bifalgorithm