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 access array elements safely in C?ComputerScienceOne · Basic Usage
- How do you deallocate dynamically allocated arrays?ComputerScienceOne · Using Arrays with Functions
- How do you dynamically allocate and initialize a structure?ComputerScienceOne · Selection Operators
- How can you check for a NULL pointer and dereference a valid pointer?ComputerScienceOne · Passing By Reference
- How do you create and use an array of structures in C?ComputerScienceOne · Arrays of Structures
- How are arrays passed to functions in C?ComputerScienceOne · Using Arrays with Functions
- Why use a contiguous memory block for a two-dimensional array?ComputerScienceOne · Contiguous 2-D Arrays
- How can pointer manipulation create a contiguous two-dimensional array?ComputerScienceOne · Contiguous 2-D Arrays