Mik*_*her 10 c c++ algorithm coding-style
问题是描述代码的作用,功能的作用.
以下代码是过去第二年C和C++模块考试试卷的一部分.任务是描述以下代码的作用.我完全按照提交的方式编写了代码,并自己添加了一些注释.
int g(int * y, unsigned size, int z) {
int tmp = y[0];
// what type is unsigned size? Int I presume. Why would you add an int to an array of ints?
int * b = y + size;
y[0] = z;
// I have the most difficulty understanding the following.
while (1) if (*(--b)==z){y[0] = tmp; return b - y;};
// are the following 3 lines ever even reached?
y[0] = tmp;
if (tmp == z) return 0;
else return -1;
}
Run Code Online (Sandbox Code Playgroud)
Rup*_*Rup 10
// what type is unsigned size?
Run Code Online (Sandbox Code Playgroud)
这是一个unsigned int
叫做的size
.您可以像在普通指针算术中一样将它添加到指针 - 将此指针前进到数组的最末端.
while (1) if (*(--b)==z){y[0] = tmp; return b - y;};
Run Code Online (Sandbox Code Playgroud)
好的,我们有
while(1)
= while(true)或'loop forever'*(--b)
预先减少b并从该数组的索引中读取值b-y
- 我们所在的数组索引的指针算法即我们正在向后扫描数组以查找最后一个实例z
并返回我们找到它的索引.我们将始终z
在数组中找到因为我们把它作为第一个元素放在那里,即如果z
不在数组中那么我们返回0.
// are the following 3 lines ever even reached?
Run Code Online (Sandbox Code Playgroud)
不,我不这么认为.
什么类型是无符号大小
unsigned
是的缩写unsigned int
.
为什么要在int数组中添加int?
指针和数组不是一回事.您展示的代码是使用指针,而不是数组.在后int * b = y + size;
线,b
是指向条目的指针size
从那里条目y
指向.例如,如果size
是2
,b
则指向第三个条目.ASCII艺术:
+---------+
| entry 0 |<--- `y` points here
| entry 1 |
| entry 2 |<--- `b` points here if `size` is `2`
| entry 3 |
| entry 4 |
+---------+
Run Code Online (Sandbox Code Playgroud)
我最难理解以下内容.
while (1) if (*(--b)==z){y[0] = tmp; return b - y;};
循环通过y
从标识的条目开始之前的条目开始查看指向的内存中的条目size
.如果该条目是==
对z
,它设置y[0]
于tmp
并返回该条目已找到索引(通过使用指针运算,b - y
返回地方之间的条目数b
指向和年初y
以来--b
递减指针时,遍历工作落后记忆.
甚至达到了以下3条线?
否.return
将退出功能当第一找到匹配条目,其可以是在开始时(如y[0]
被设定为z
早于).正如Ted Hoff在评论中指出的那样,循环将开始并继续超过开始(y
指向的位置),如果size
正在0
进入,这可能最终导致程序因内存访问冲突而失败.
这段代码的第一件事就是证明作者是无能的.但我认为这是作业的一部分:理解由无能的人写的代码.
对于初学者:
unsigned
是一个有效的C++类型,收缩unsigned int
.除非你做一点操作,否则通常最好避免.
您的代码中没有数组; 你正在向指针添加一个整数.而且奇怪的[]
是,不是数组索引,而是
定义a[b]
为完全等同于*(a+b)
.(至少对于类型的构建.)你可能想找一本关于C的书来解释这个; 在C++中,我们通常使用std::vector
,正是为了避免所有这些关于指针算术的混淆.
至于你难以理解的部分:对于初学者,让我们以理智的方式写出来:
while ( true ) {
-- b;
if ( *b == z ) {
y[0] = tmp;
return b - y;
}
}
Run Code Online (Sandbox Code Playgroud)
关于唯一应该导致问题的是return语句:这是指针减法; 在这种情况下,因为y
是数组的第一个元素(从代码的其余部分判断),所以b - y
计算指向的元素的索引b
.
这里指针的使用将是纯粹的混淆,除了成语在C中无处不在,并且在C++中使用迭代器进行.
你是对的,循环后的代码永远不会被执行; 离开循环的唯一方法是通过return
.
编写循环的更简洁的方法是:
int i = size;
while ( i != 0 && y[i - 1] != z ) {
-- i;
}
y[0] = tmp;
return i;
Run Code Online (Sandbox Code Playgroud)