我想用malloc为二维指针分配内存,但是调试时发现分配似乎不对或者清空有问题,以下是调试的情况和源码:
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
int** a, n;
bool** b;
void creatalp() {
a = (int**)malloc(sizeof(int) * n * n);
b = (bool**)malloc(sizeof(bool) * n * n);
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
}
void putalp() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%2d", a[i][j]);
if (j < n - 1) printf(" ");
}
if (i < n - 1) printf("\n");
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while (cin >> n, n != 0) {
creatalp();
int t = n / 2, k = 0, ans = 2, sum = 1;
a[0][t] = 1, b[0][t] = true;
for (int i = k; i < n;) {
for (int j = t; j < n;) {
if (k == 0 && j == n - 1 || b[i - 1][j + 1] == true) {
i++;
}
else {
t == n - 1 ? t = 0 : t++;//control the column
k == 0 ? k = n - 1 : k--;//control the line
}
a[i][j] = ans++;
b[i][j] = true;
sum++;
break;
}
if (sum == n * n) break;
}
putalp();
}
return 0;
}
求指教