繁体   English   中英

For循环无效,而while循环有效

[英]For loop doesn't work but while loop does

我创建了一个在特殊区域周围创建边框的函数(这些信息存储在下表的结构中):

typedef struct s_letter_stock
{
    int element_nb;
    int width;
    int height;
    t_pos square_p1;
    t_pos square_p2;
} g_letter_stock;
//those values are for the example
g_letter_stock letter_infos[] = {{ 0, 0, 0, {0, 0}, {0, 0} },
                                 { 0, 0, 0, {0, 0}, {0, 0} }};

我发现了一个疯狂的错误:下面的函数中的for loop在第一次运行时效果很好,但随后又停止了,就像循环结束时出现了中断(当我打印nb_elem它的值正确)。 因此,基本上我不知道为什么for (在注释中)工作while停止。 您对此怪异行为有任何想法吗? 我没主意了。

void create_borders(char **map, int nb_elem)
{
    printf("nb_elem : %d\n", nb_elem);
    for (int i = 0 ; i < nb_elem ; i++) //THIS dosnt work and stop once i = 1
        // int i = 0;                    //ALL the commentes are part of the other
        // int j = 0;                    //solution that i found which is working
        // while (j < nb_elem)
    {
        int newx = -1;
        int newy = -1;
        while (newx <= letter_infos[i].width + 1 ||
               newy <= letter_infos[i].height + 1)
        {
            if (letter_infos[i].square_p1.y - 1 >= 0 &&
                newx <= letter_infos[i].width + 1)
                map[letter_infos[i].square_p1.y - 1][letter_infos[i].square_p1.x + newx] = '@';
            if (letter_infos[i].square_p1.x - 1 >= 0 &&
                newy <= letter_infos[i].height + 1)
                    map[letter_infos[i].square_p1.y +
                        newy][letter_infos[i].square_p1.x - 1] = '@';
            if (letter_infos[i].square_p2.y + 1 < strlen (map[0]) &&
                newx <= letter_infos[i].width + 1)
                map[letter_infos[i].square_p2.y + 1][letter_infos[i].square_p2.x - newx] = '@';
            if (letter_infos[i].square_p2.x + 1 < my_tablen (map) &&
                newy <= letter_infos[i].height + 1)
                map[letter_infos[i].square_p2.y - newy][letter_infos[i].square_p2.x + 1] = '@';
            newx++;
            newy++;
        }
        printf ("i = %d\n", i);
        i++;
        //j++;
    }
}

您需要删除以下语句:

i++;

for循环的底部,因为您已经在for条件的第三部分中增加了i

我看到每个循环都有2个执行时间i++ (在for (int i = 0 ; i < nb_elem ; i++)和循环结束时)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM