gpt4 book ai didi

c - 在for循环中初始化变量(圆括号内)和在for循环之前初始化变量有什么区别吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:52 26 4
gpt4 key购买 nike

给定一段代码:

void twoDimFunc(int (*p)[HEIGHT])
{
int i = 0, j = 0;
for (;i < WIDTH ; i++)
for (;j < HEIGHT; j++)
{
*((int*)p + i * HEIGHT + j) = -1;
}

}

在 main() 程序中我调用这个函数,然后输出矩阵,然后我在 stdout 中得到如下矩阵:

-1 -1 -1
0 0 0

但是,对于这段代码

void twoDimFunc(int (*p)[HEIGHT])
{
int i = 0, j = 0;
for (i = 0;i < WIDTH ; i++)
for (j = 0;j < HEIGHT; j++)
{
*((int*)p + i * HEIGHT + j) = -1;
}

}

输出是

-1 -1 -1
-1 -1 -1

for 循环圆括号内的初始化行为是否与 for 循环之前的初始化行为不同?

谢谢。

最佳答案

这两个代码有不同的行为。在这段代码中:

void twoDimFunc(int (*p)[HEIGHT])
{
int i = 0, j = 0;
for (i = 0;i < WIDTH ; i++) //loop 1
for (j = 0;j < HEIGHT; j++) //j = 0 at each turn of loop 1
{
*((int*)p + i * HEIGHT + j) = -1;
}

}

j 在您提供的第一个代码中永远不会重新初始化为 0:

void twoDimFunc(int (*p)[HEIGHT])
{
int i = 0, j = 0;
for (;i < WIDTH ; i++) //loop 1
for (;j < HEIGHT; j++) //j isn't initialized to 0 for each turn of loop 1
{
*((int*)p + i * HEIGHT + j) = -1;
}

}

关于c - 在for循环中初始化变量(圆括号内)和在for循环之前初始化变量有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23129941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com