Question & Answer: O 30 io int | int |…..

A multidimensional array question in C:

I need to create a 2D array as follows:

A 2 dimensional array can be malloced. Inside each value i.e. array[1][1] I need another 1 dimensional array that can hold 2 integers and a pointer to another array that will hold sepearate values.

How would I implement this?

O 30 io int | int |s

O 30 io int | int |

Expert Answer

 

typedef struct my_struct{

int a[2];

int *ptr;

} STRUCT;

 

STRUCT** alocate(int row, int col) {

STRUCT** arr;

int i;

 

arr = (STRUCT**)malloc(sizeof(STRUCT*) * row);

for (i = 0; i < row; i++) {

arr[i] = (STRUCT*)malloc(sizeof(STRUCT) * col);

}

}

/*

row = 2, col = 4

malloc(sizeof(STRUCT*) * row);

==========

|        |

|        |

| arr[0] |

|        |

==========

|        |

|        |

| arr[1] |

|        |

==========

 

for (int i = 0; i < row; i++) {

arr[i] = (STRUCT*)malloc(sizeof(STRUCT) * col);

==========          ========================================

|        |          |         |         |         |         |

|    <==============|         |         |         |         |

| arr[0] |          |arr[0][0]|arr[0][1]|arr[0][2]|arr[0][3]|

|        |          |         |         |         |         |

==========          =========================================

|        |          |         |         |         |         |

|    <==============|         |         |         |         |

| arr[1] |          |arr[1][0]|arr[1][1]|arr[1][2]|arr[1][3]|

|        |          |         |         |         |         |

==========          ==========================^==============

|———–int, int, int*

*/

View this in a text editor like notepad or gedit or vim

Still stressed from student homework?
Get quality assistance from academic writers!