I am interested in how to organize the initialization of a two-dimensional array using pointers.

int main(){ float a[N][N]; int n; clrscr(); n = setsize(n); arndom(a, n); getch(); return 0; } void arndom(float **array, int size){ float **str_scan, *stol_scan; srand(time(NULL)); printf("Source array:\n"); for(str_scan = array; str_scan < &array[size][size]; str_scan++){ for(stol_scan = *str_scan; stol_scan < &array[str_scan - array][size]; stol_scan++){ stol_scan = rand() % -99,9 - 99,9; printf("%.2f ", *stol_scan); } printf("\n"); } } 

1 answer 1

Multidimensional array - int a[N][M];

It is good to use when the size is known at compile time. Example:

 int a[2][3]; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) a[i][j] = (i + 1) * (j + 1); } for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) printf("%d ", a[i][j]); printf("\n"); } 

Memory for such an array is released automatically after the completion of the execution of the block of code where it was declared.

Array of pointers to a pointer - int ** a;

It is good to use when the size of the array is not known at compile time. Example:

 int ** a; int N = 2, M = 3; //Допустим эти значСния ΡΡ‡ΠΈΡ‚Ρ‹Π²Π°ΡŽΡ‚ΡΡ ΠΎΡ‚ΠΊΡƒΠ΄Π° Ρ‚ΠΎ Π²ΠΎ врСмя Ρ€Π°Π±ΠΎΡ‚Ρ‹ ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹... int i, j; a = calloc(N, sizeof(int*)); //Π²Ρ‹Π΄Π΅Π»Π΅Π½ΠΈΠ΅ массива ΡƒΠΊΠ°Π·Π°Ρ‚Π΅Π»Π΅ΠΉ. for (i = 0; i < N; i++) a[i] = calloc(M, sizeof(int)); //Π²Ρ‹Π΄Π΅Π»Π΅Π½ΠΈΠ΅ массива int'ΠΎΠ², Π² элСмСнтС массива ΡƒΠΊΠ°Π·Π°Ρ‚Π΅Π»Π΅ΠΉ. for (i = 0; i < N; i++) { for (j = 0; j < M; j++) a[i][j] = (i + 1) * (j + 1); } for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf("%d ", a[i][j]); printf("\n"); } for (i = 0; i < N; i++) { free(a[i]); //освобоТдСниС массива int'ΠΎΠ² Π² массивС ΡƒΠΊΠ°Π·Π°Ρ‚Π΅Π»Π΅ΠΉ } free(a); //осовобоТдСния массива ΡƒΠΊΠ°Π·Π°Ρ‚Π΅Π»Π΅ΠΉ