【问题标题】:Why this code is working for 1 and 2 yet fails for input that is more than 3?为什么此代码适用于 1 和 2 但输入超过 3 时失败?
【发布时间】: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&lt;temp2;j++) 中)?
  • 先看看你的内存分配你需要(n+1)*(n+1)个地方。
  • @JaMiT 说明igoe.exe已经停止工作。返回255

标签: c nested-loops


【解决方案1】:

最好按轴检查距离并打印最多的距离。

类似:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int vertical_distance;
    int horizontal_distance;
    
    int n;
    scanf("%d",&n);
    for(int i = 0; i < n * 2 + 1; i++)
    {
        for(int j = 0; j < n * 2 + 1; j++)
        {
            vertical_distance   = abs(n - i);
            horizontal_distance = abs(n - j);
            if (vertical_distance > horizontal_distance)
                printf("%d ", vertical_distance);
            else
                printf("%d ", horizontal_distance);
        }
        printf("\n");
    }
    return(0);
}

此外,当我运行您的代码时,它可以很好地处理大数字(3、7、15)。 我刚刚将您的代码粘贴到 onlinegdb.com/online_c_compiler 并运行它。您能否添加您收到的错误消息?

(对不起我的英语)

【讨论】:

  • 数组大小分配错误,所以程序就像 .exe 文件停止工作一样崩溃了。这是一个更优雅的解决方案。谢谢。 PS:你的英文很好。
【解决方案2】:

在这段代码中

for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
{
      arr[j] = n;
}

j 可以大于 n。但是 arr malloc 空间是 n。数组溢出。

只需稍作改动即可使用

arr = (int*)malloc(2*n*sizeof(int));

【讨论】:

  • 感谢您指出这一点!实际上适用于 (2*n-1)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2017-09-18
  • 2017-03-02
  • 2016-02-27
  • 2015-07-18
相关资源
最近更新 更多