【发布时间】:2021-05-30 01:17:56
【问题描述】:
所以我正在尝试用 C 打印模式。
For n = 2
Output:
2 2 2
2 1 2
2 2 2
for n = 3
Output:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
and so on.
我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d",&n);
int nn = n;
int *arr;
arr = (int*)malloc(n*sizeof(int));
int f = 0; //flag to check if I reached the mid of the pattern
int l = 2*n-1; //Lenght of square to be generated
int temp1 = 0;
int temp2 = l;
for(int i = 0;i<l;i++)
{
for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
{
arr[j] = n;
}
for(int k = 0;k<l;k++)
{
printf("%d ",arr[k]);
}
printf("\n");
if(n == 1)
{
f = 1;
}
if(f==0) //For upper half of pattern
{
n=n-1;
temp1=temp1+1;
temp2=temp2-1;
}
else if(f==1) //For lower half of pattern
{
n=n+1;
temp1=temp1-1;
temp2=temp2+1;
}
}
return(0);
}
我得到了 n = 2 的正确输出,但是当我输入 2 以上的任何内容时,代码就会崩溃。 我无法找到应该做什么。有人可以帮助我并告诉我我做错了什么吗?
【问题讨论】:
-
你能找出是哪一行触发了崩溃吗?该行中出现的变量的值是多少?
-
首先,你试过用纸笔解决它吗?然后,您是否尝试过使用调试器逐句执行代码语句,同时监视变量及其值(并确保您的代码执行它应该执行的操作,并遵循您使用笔和纸提出的操作)?
-
一个提示:你为
arr分配了多少元素?您实际使用了该数组的多少个元素(例如在循环for(int j = temp1;j<temp2;j++)中)? -
先看看你的内存分配你需要(n+1)*(n+1)个地方。
-
@JaMiT 说明igoe.exe已经停止工作。返回255
标签: c nested-loops