Summary ARRAYS IN DATA STRUCTURE
Declaration and Initialization of Arrays Arrays are used to store multiple items of the same data type. In C, arrays can be declared as follows: data_type array_name[array_size]; Here, data_type is the type of data that the array will store, array_name is the name of the array, and array_size is the number of elements that the array can hold. For example, the following code declares an array numbers that can hold 5 integers: int numbers[5]; Initialization of Arrays Arrays can be initialized using the following syntax: data_type array_name[array_size] = {value1, value2, ..., valueN}; Here, value1 to valueN are the initial values for the elements of the array. The number of values must be less than or equal to array_size. If you don't specify any values, all the elements of the array will be initialized to 0. For example, the following code declares and initializes an array numbers with the values 1, 2, 3, 4, and 5: int numbers[5] = {1, 2, 3, 4, 5}; Multi-dimensional Arrays Arrays can also be multi-dimensional, i.e., an array of arrays. A two-dimensional array can be declared as follows: data_type array_name[x][y]; Here, x and y are the number of rows and columns of the array, respectively. Multi-dimensional arrays can be initialized similarly to one-dimensional arrays, by specifying the values for each element. For example, the following code declares and initializes a 2x2 array matrix: int matrix[2][2] = {{1, 2}, {3, 4}}; Memory Representation of Arrays Arrays are stored in contiguous memory locations. This means that the elements of an array are stored in adjacent memory locations, which allows for efficient access and traversal of the array. The starting address of the array is the address of its first element, and the address of each subsequent element can be calculated by adding the size of the data type to the address of the previous element. For example, consider the following 1-dimensional array: int numbers[3] = {1, 2, 3}; The memory representation of this array would look like the following: | Address | Value | | --- | --- | | 1000 | 1 | | 1004 | 2 | | 1008 | 3 | The starting address of the array is 1000, and each integer is stored in 4 bytes of memory. The second element has an offset of 4 bytes (the size of an integer) from the first element, and the third element has an offset of 8 bytes. Note that this description is a simplification, as the actual memory address and layout may vary depending on the system and compiler. The important takeaway is that the elements of an array are stored in contiguous memory locations, which allows for efficient array traversal and operations.
Written for
- Institution
- University Of The People
- Course
- ARRAYS IN DATA STRUCTURE (CSE)
Document information
- Uploaded on
- July 8, 2024
- Number of pages
- 2
- Written in
- 2023/2024
- Type
- SUMMARY
Subjects
- array
- datastructure
-
declaration and initialization of array
-
memory representation of arrays