程序执行不起来。
题目
1 <= n <= 20
#include <stdio.h>
#include <stdlib.h>
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
{
if (n <= 0)
{
*returnSize = 0;
*returnColumnSizes = NULL;
return NULL;
}
int** res = (int**)malloc(n * sizeof(int*));
if (res == NULL)
{
*returnSize = 0;
*returnColumnSizes = NULL;
return NULL;
}
for (int i = 0; i < n; i++)
{
res[i] = (int*)malloc(n * sizeof(int));
if (res[i] == NULL)
{
free(res[i]);
}
else
{
for (int j = 0; j < n; j++)
{
res[i][j] = (int)malloc(sizeof(int));
}
}
}
int a1 = n;
int a2 = n - 1;
int f = 1;
int c1 = 0, c2 = 0;
int w = 1;
while (a1 > 0 || a2 > 0)
{
for (int i = 0; i < a2; i++)
{
res[c1][c2] = w;
c2 = c2 + f;
w++;
}
for (int i = 0; i < a1; i++)
{
res[c1][c2] = w;
c1 = c1 + f;
w++;
}
a2--;
a1--;
f = -f;
}
returnSize =&n;
for (int i = 0; i < n; i++)
{
(*returnColumnSizes)[i] = n;
}
return res;
}
int main() {
int n;
printf("Please enter a number for the size of the matrix:\n");
scanf_s("%d", &n);
int returnSize;
int* returnColumnSizes;
int** res = generateMatrix(n, &returnSize, &returnColumnSizes);
if (res == NULL)
{
printf("ERROR: Failed to allocate memory.\n");
return -1;
}
for (int i = 0; i < returnSize; i++)
{
for (int j = 0; j < returnColumnSizes[i]; j++)
{
printf("%d ", res[i][j]);
}
printf("\n");
}
for (int i = 0; i < returnSize; i++)
{
free(res[i]);
}
free(res);
free(returnColumnSizes);
return 0;
}
想问怎么解决这个问题?