The task is to derive a square matrix in a spiral counterclockwise. I wrote for the static matrix, I need to change for the dynamic I tried but replacing just the static with the dynamic one, only the first element is output.

#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int n; int i, j, x = 0, y = 0,w = n-1,l = 0; // w - отступ от дального столбца l - от верхней строки srand(time(NULL)); printf("Введите размер матрицы\n"); scanf("%d",&n); int **mas = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; i++) mas[i] = (int *)malloc(n * sizeof(int)); for ( i = 0; i < n; i++) { for (int j = 0; j < n; j++) { mas[i][j] = rand() % 100; printf("%d ",mas[i][j] ); } printf("\n"); } for (i=0; i<n*n; ++i) { printf("%d ", mas[x][y]); if ((y==(l+1))&&(x==l)) {w--;l++;} //условие перехода на внутренюю спираль if ((x==w)&&(y<w)) {y++;continue;} //вниз if ((x<w)&&(y==l)) {x++;continue;} //вправо if ((y==w)&&(x>l)) {x--;continue;} //влево if ((x==l)&&(y>l)) {y--;continue;} //вверх } return(0); } 
  • Offhand: int n; /* ... */ int w = n-1 int n; /* ... */ int w = n-1 - what is the value of n at this moment? That's right, uncertain :) - PinkTux

1 answer 1

Error here:

 int n; int i, j, x = 0, y = 0, w = n - 1, l = 0; ^^^^^^^^^ 

The variable w initialized with the garbage value, since the value of n is undefined at this moment. This is how it works:

 scanf("%d",&n); w = n - 1; /* ... */ 83 86 77 15 93 35 86 92 49 83 15 86 92 49 35 77 86 93 

Well, I should add:

 #include <time.h> /* time() */ #include <stdlib.h> /* malloc(),free(),srand(),rand() */