我試圖遞歸修改2D char數組(字符串數組),但在第一次遞歸調用後,數組返回空白,即使在基本情況下的更改註冊在遞歸函數中修改2d數組,C
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]);
}
}
爲什麼數組復位?我無法想象它會是一個範圍問題,因爲數組本身在函數中聲明。目的是打印一個分形三角形,因此不需要將二維數組傳遞給函數,我只是想遞歸地創建模式。我正在一點一點地做這件事(遞歸仍然不完整) - 現在我只是測試一下數組是否可以保持來自呼叫。
事實上,它實際上是在第一次遞歸後打印垃圾值,就好像它並沒有在第一次初始化時那樣。 –
由於數組trianglePattern位於fractalTriangle例程的本地,並且未聲明爲「靜態」,因此每個遞歸調用都會在其自己的未初始化的本地數組版本上運行,並且結果將不會以您期望的方式傳播。 –
表達式*局部變量*響鈴嗎? –