dynamic memory allocation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | #include <stdio.h> #include <stdlib.h> #include <time.h> void** Create_Array (void** _Array, int _Size_Of_Row, int _Size_Of_Column, int Size_Of_Data_Type); void Delete_Array (void** _Array); void Print_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column); void Write_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column); int Sum_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column); int main(void) { int Size_Of_Row = 0, Size_Of_Column = 0; // input, use scanf (); Size_Of_Row = 3, Size_Of_Column = 5; // create array int** _Array = (char) 0; _Array = (int**) Create_Array ((void**)_Array, Size_Of_Row, Size_Of_Column, sizeof (int)); // write random data Write_Array (_Array, Size_Of_Row, Size_Of_Column); // print data Print_Array(_Array, Size_Of_Row, Size_Of_Column); // Sum printf ("Sum : %d\n", Sum_Array (_Array, Size_Of_Row, Size_Of_Column)); // free memory Delete_Array ((void**)_Array); return 0; } int Sum_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column) { int sum = 0; int row = 0, column = 0; for (column = 0; column < _Size_Of_Column; column++) { for (row = 0; row < _Size_Of_Row; row++) { sum += *(*(_Array + column) + row); } } return sum; } void Write_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column) { (void)srand((unsigned)time((char)0)); int row = 0, column = 0; for (column = 0; column < _Size_Of_Column; column++) { for (row = 0; row < _Size_Of_Row; row++) { int Random_Number = (rand() % 100) + 1; *(*(_Array + column) + row) = Random_Number; } } return; } void Print_Array (int** _Array, int _Size_Of_Row, int _Size_Of_Column) { // print data int row = 0, column = 0; for (column = 0; column < _Size_Of_Column; column++) { for (row = 0; row < _Size_Of_Row; row++) { printf("%3d", *(*(_Array + column) + row)); } printf("\n"); } return; } void Delete_Array (void** _Array) { // free memory int column = 0; while (*(_Array + column++) != (char)0) { if (*(_Array + column) != (char)0) *(_Array + column) = (char)0; free(*(_Array + column)); } if (_Array != (char)0) _Array = (char)0; free(_Array); return; } void** Create_Array (void** _Array, int _Size_Of_Row, int _Size_Of_Column, int Size_Of_Data_Type) { // Dynamic memory allocation _Array = (void**)calloc(_Size_Of_Column, sizeof(void*)); int column = 0; for (column = 0; column < _Size_Of_Column; column++) { *(_Array + column) = (void*)calloc(_Size_Of_Row, Size_Of_Data_Type); } return (void**)_Array; } | cs |
0 개의 댓글:
댓글 쓰기