Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I am supposed to simulate a cache using C. I understand that I would create 2

ID: 3872506 • Letter: S

Question

So I am supposed to simulate a cache using C. I understand that I would create 2 dimenional arrays, but do not understand how I would incorporate pointers to pointers (**) and malloc to do so. Below is the description of the part of the assignment that I am confused about;

The state of the cache will be stored in two dynamically sized arrays: tagArray and status of the line in set i, way j. To give you experience with pointers and malloc) these should be implemented using pointers (scheduled to be covered in Lecture 3 or 4) In particular, declare unsigned int **tagArray and int **1ruArray and use malloc)

Explanation / Answer

Here by double pointer(**) they mean that we have to define a array of pointers using this double pointer. Each pointer in this array of pointers will point to an array of holding the actual data we are refering to. I am writing a small code here to make this concept more clear to you.

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int r = 2, c = 2, i, j, count;

    int **arr = (int **)malloc(r * sizeof(int *)); // Array of pointers allocated dynamically

    for (i=0; i<r; i++)

         arr[i] = (int *)malloc(c * sizeof(int)); //Allocating an array of integer to each pointer in the pointer of arrays

count = 0;

    for (i = 0; i < r; i++)

      for (j = 0; j < c; j++)

         arr[i][j] = ++count; // We can also use *(*(arr+i)+j) = ++count

    for (i = 0; i < r; i++)

      for (j = 0; j < c; j++)

         printf("%d ", arr[i][j]);

   return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote