需要帮助了解code在C指针和数组 [英] Need help to understand the code with pointers and arrays in c
本文介绍了需要帮助了解code在C指针和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要了解注释行做什么?
的#include<&stdio.h中GT;
无效的乐趣(字符**);诠释的main()
{
的char * argv的[] = {AB,CD,EF,GH};
有趣(ARGV);
返回0;
}
无效的乐趣(字符** P)
{
字符*吨;
T =(P + = sizeof的(INT)) - 1]; //这一行做了什么? // [ - 1]做什么?
的printf(%S \\ n,T);
}
解决方案
假设 INT
是在你的机器4个字节,然后替换的sizeof( INT)
以4:
T =(P + = 4)) - 1];
只是继续前进的指针 P
4个元素,而向后移动1元,然后得到的元素。
在这个例子中,数组有4个元素,这样向前移动一个过去的结束,向后移动到最后一个元素,它是GH
。
若干注意事项:
-
A [-1]
就是*(A - 1)。
- 您需要确保当你做指针算法,他们总是在一个阵列或者一个过去的结束指向一个元素。
- 同样的名称
的argv
不是一个好主意,因为我们通常用它来
参考的参数主
。
I need to understand what the commented line does?
#include <stdio.h>
void fun(char**);
int main()
{
char *argv[] = {"ab", "cd", "ef", "gh"};
fun(argv);
return 0;
}
void fun(char **p)
{
char *t;
t = (p+= sizeof(int))[-1]; //what this line does? //[-1] does what?
printf("%s\n", t);
}
解决方案
Assuming that int
is 4 bytes in your machine, then replace sizeof(int)
with 4:
t = (p+= 4))[-1];
is just to move forward the pointer p
4 elements, and move backward 1 element, then get the element.
In this example, the array has 4 elements, so move forward to one past the end, and move backward to the last element, which is "gh"
.
Several note:
a[-1]
is just*(a - 1)
.- You need to make sure when you do pointer arithmetic, they are always pointing an element in an array or one past the end.
- Also the name
argv
is not a good idea, since we usually use it to refer to the parameter ofmain
.
这篇关于需要帮助了解code在C指针和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文