# Arrays: Memory

## Contents

#### Problems and Solutions 1

Problem : What is the difference between the following two chunks of code:

```
if (arr1 == arr2) {
process();
}
```
```
if (! memcmp(arr1, arr2, n * sizeof(int))) {
process();
}
```
Assuming arr1 and arr2 are both integer arrays of length n.

The first code fragment does not compare the data in the arrays, but merely the address value stored in each array, meaning the location in memory where each array begins. Thus in the first code fragment, process() will only be called if both arrays start at the same memory location. In the second one, it actually compares the first n integers in the two arrays and thus process() will be called if the two arrays contain the same data, regardless of whether the two arrays are actually the same chunks of memory.

Problem : Write code that will make a copy of int arr[SIZE] and point the array int arr_new[] to it.

Simply saying:
```
arr_new = arr;
```
will only make it so that both arrays point to the same chunk of memory. To make new memory, you first need to call malloc. Then you need to copy the data from one chunk of memory into the other.
```
if (! (arr_new = malloc (SIZE * sizeof(int)))) {
/* Memory allocation failed, exit with error status. */
exit 1;
}

for (i = 0; i < SIZE; i++) {
arr_new[i] = arr[i];
}
```
Notice that it would also be possible to use functions such as memcpy to copy chunks of memory from one location to another.