BUPT-homework/semester1/pset13/1-3-DynamicMemoryAllocation.c

88 lines
1.7 KiB
C
Raw Permalink Normal View History

2021-12-09 17:26:31 +08:00
#include <stdio.h>
#include <stdlib.h>
char **create1(int n);
void create2(char **strPtr, int n);
void fill(char **strPtr, int n);
int main() {
int n, i, j;
char **strPtr;
scanf("%d", &n);
strPtr = create1(n * 2 + 1);
create2(strPtr, n * 2 + 1);
fill(strPtr, n);
for (i = 0; i < 2 * n + 1; i++) {
printf("%s\n", strPtr[i]);
}
for (i = 0; i < n * 2 + 1; i++)
free(strPtr[i]);
free(strPtr);
return 0;
}
/* 请在这里填写答案 */
char **create1(int n) {
char **strPtr =
malloc(sizeof(char *) * n); // This char * is soooooo important
return strPtr;
}
void create2(char **strPtr, int n) {
for (int i = 0; i < n; i++) {
strPtr[i] = malloc(sizeof(char) * (n + 1));
}
}
void fill(char **strPtr, int n) {
int loc;
if (n == 0) { // Take care of special case
strPtr[0][0] = 'X'; // When n == 0, it is only X
return;
}
for (int i = 0; i <= n; i++) {
loc = 0;
for (int j = 0; j < n - i; j++) {
strPtr[i][loc++] = ' ';
}
if (i % n == 0) {
strPtr[i][loc++] = 'X';
} else {
strPtr[i][loc++] = '/';
}
for (int j = 0; j < 2 * i - 1; j++) {
strPtr[i][loc++] = ' ';
}
if (i != 0) {
if (i == n) {
strPtr[i][loc++] = 'X';
} else {
strPtr[i][loc++] = '\\';
}
}
strPtr[i][loc] = '\0'; // EOL
}
for (int i = n + 1; i < 2 * n + 1; i++) {
loc = 0;
for (int j = 0; j < i - n; j++) {
strPtr[i][loc++] = ' ';
}
if (i != n * 2) {
strPtr[i][loc++] = '\\';
} else {
strPtr[i][loc++] = 'X';
}
for (int j = 0; j < -2 * (i - n) + 2 * n - 1; j++) {
strPtr[i][loc++] = ' ';
}
if (i != 2 * n) {
strPtr[i][loc++] = '/';
}
strPtr[i][loc] = '\0'; // EOL
}
}