我正在尝试递归修改 2D char 数组(字符串数组),但在第一次递归调用后,即使更改在基本情况下注册,数组仍返回空白
int main(int argc, const char * argv[]) {
int height;
printf("Enter the height of your triangle.\n");
scanf("%d", &height);
printf("Lets see if you were successful!\n");
fractalTriangle(height, 1);
}
void fractalTriangle (int height, int fractalLevel) {
//has to make the array and do the printing all in the same function
char trianglePattern [height][2 * height - 1];
if (fractalLevel == 0) {
int rowSize = 2 * height - 1;
char rowString[rowSize]; //string to store in pattern's array
int asteriskCount = 1; //number of asterisks printed in each row
int spaces = (rowSize - asteriskCount) / 2; //how many spaces need to be printed in this current row
int rowCount;
for (rowCount = 0; rowCount < height; rowCount++) {
char *ptr = trianglePattern[rowCount];
int counter = 0;
int astCounter = 0;
int spCounter = 0;
while (spCounter < spaces) {
if (counter == 0) {
strcpy(rowString, " ");
}
else {
strcat(rowString, " ");
}
counter++;
spCounter++;
}
while (astCounter < asteriskCount) {
if (counter == 0) {
strcpy(rowString, "*");
}
else {
strcat(rowString, "*");
}
counter++;
astCounter++;
}
spCounter = 0;
while (spCounter < spaces) {
strcat(rowString, " ");
spCounter++;
}
asteriskCount+=2;
spaces--;
strcpy(ptr, rowString);
//printf("%s\n", trianglePattern[rowCount]);
//printf("%s\n", rowString);
}
}
else {
fractalTriangle(height/2, fractalLevel - 1);
printf("%s\n", trianglePattern[0]);
printf("%s\n", trianglePattern[1]);
printf("%s\n", trianglePattern[2]);
printf("%s\n", trianglePattern[3]);
}
为什么阵列会重置?我无法想象这会是一个范围问题,因为数组本身是在函数中声明的。目的是打印分形三角形,因此无需将二维数组传递给函数,我只想递归地创建图案。我正在一点一点地做这件事(递归仍然不完整)——现在我只是在测试以查看数组是否从调用到调用保持不变。
最佳答案
由于您在函数范围内定义数组,每个函数都会在堆栈上创建一个新的二维字符数组。该函数将仅对二维字符数组的那个 实例进行操作。到递归存在时,打印原始未修改的二维字符数组。
您需要在递归函数之外定义一个字符数组,然后将该字符数组(或者更确切地说是指向它的指针)传递给递归函数。
关于c - 在递归函数中修改二维数组,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33289548/