Dynamic Alloc

Lesson

코딩도장 핵심요약: 구조체 포인터 메모리 할당

We have used fixed sized 1-D or 2-D arrays

double a[4] = { 2, 2, 3, 4 };

How can the user set the size of the array i.e., change the value of m by n) during the run-time? Is it possible to declare arrays without knowing its size?

malloc()

void * malloc(size_t size);	

Characteristics of “void * ” type (void pointer type)

  • void pointer type can be assigned arbitrary types

  • void pointer type can perform pointer operations

  • in order to use the void pointer type properly, casting is necessary

  • returns a pointer to the allocated memory, or NULL if the request fails

Example:

//** 1D Array
(int *)malloc(sizeof(int) * (_row));

//** 2D Array
// 1. allocate row array first
matA = (int**)malloc(sizeof(int*) * (_row));
// 2. Then, allocate column 
for(int i = 0; i < _row; i++)	
    (matA)[i] = (int*)malloc(sizeof(int) * (_col));

Example Code

Example 1

Dynamic Allocation- 1D using functions

C_malloc1d_example.c

Example 2

Dynamic Allocation- 1D using functions

C_malloc1d_example2.c

Example 3

Dynamic Allocation- 2D using functions

C_malloc2d_example2.c

You are passing ‘int *mat’ to the function ‘create_mat( )’ without allocating size and memory of the 2-D array. Thus, you need to pass the address of ‘int **mat’ as ‘**&mat’ and the function receives it as ‘int* _mat’ (3 pointer notation)

Notice how different ‘malloc’ syntax is used in ‘Main()’ function and in ‘create_mat()’ function. Once, the memory of 2-D is allocated then you can pass the array to a function as

Example 4

Structure Dynamic Allocation- 2D Matrix

C_matrix_example.c

Example 5

Structure Dynamic Allocation- 2D Matrix

myMatrix_ tutorial.h

myMatrix_ tutorial.c

C_matrix_example2.c

Exercise

Exercise 1

Download the following files

Include “myMatrix_tutorial.h” and add following functions

Matrix subMat (Matrix _A, Matrix _b);

Add two matrices of 3x3 size.

  • You can create any value 2D matrix of integer type

  • Print the input matrix and output matrix

Create a function that subtracts two matrices

Last updated

Was this helpful?