Title: More on Arrays: MultiDimensional Arrays, Arrays are Parameters
1More on ArraysMulti-Dimensional Arrays,Arrays
are Parameters
2Remember 2D Arrays?
int m20050 // 2D array float
far102032 // 3D array void func()
int i, j for (i0ilt200i) for
(j0jlt50j) mij 10 i
2j
32D Arrays in Memory
- This is how a 2D array is kept in memory.
- Each element is kept in consecutive positions in
memory.
int m32
Memory
m00
m01
m10
m11
m20
m21
Size of an int
4Pseudo 2D Arrays
- You can also define a one-dimensional array in
the following way. - You use it as though it is a two-dimensional
array. - You index the array by calculating your own
offset index to the array.
define WIDTH 5 define HEIGHT 3 int iarray
HEIGHT WIDTH int n,m int main ()
for (n0nltHEIGHTn) for
(m0mltWIDTHm)
iarraynWIDTHm(n1)(m1)
return 0
5Passing Array as Argument
- We have done this before.
- Remember, the name of the array also refers to
the address of the first element of the array. - Therefore, we can pass the name of the array as
though it is a pointer.
void printarray (int arr, int length)
for (int n0 nltlength n)
printf(d , arri)
printf(\n)
6Clearer Way
- The preceding way, though it works, is kind of
weird. - It requires you to think of a pointer as an
array, and vice versa. - When writing a function that accepts an array as
an argument, it makes more sense for the
programmer to write it in such a way that make it
clear that it is expecting an array.
void printarray (int arr, int length)
for (int n0 nltlength n)
printf(d , arri)
printf(\n)
7Multi-Dimensional Arrays as Arguments
- A procedure in C can also accept a
multi-dimensional array as an argument. - The number of elements in the higher dimensions
have to be specified in the function signature.
void procedure (int myarray34)
8malloc and free
void malloc ( size_t size )
void free ( void ptr )
- malloc requests some memory from the Operation
System and returns the address of the memory
allocated. - free frees up the space previously received by
malloc.
void func(int n) int i int iptr
iptr (int )malloc(nsizeof(int)) for
(i0iltni) iptri 15 i 2
free(iptr)
9The NULL Pointer
- malloc returns the address of the memory that has
been allocated. - However, sometimes it fails.
- For example, when the heap is full, or when
malloc requests too much memory, the OS cannot
give malloc the memory. - In this case, the return value of malloc is the
NULL pointer.
void func(int n) int i int iptr
iptr (int )malloc(nsizeof(int)) if
(iptr ! 0) // check that malloc did not return
the NULL pointer for (i0iltni)
iptri 15 i 2
free(iptr)