c++ - 我不明白的指针函数;(

标签 c++ pointers

我今天从老师那里得到了这个功能:

int nums[] = { 9, 5, 4, 2, 8, 1, 3, };
int *p = nums;
int tmp_num = *(p + 2);

p = &nums[0];       
*p = *p + *(p + 1);

++p;            
++(*p);         

*(p + 2) = 7;   

p = &nums[5] + 1;   
*p = 4;             

int size = sizeof nums / sizeof nums[0];
for (int i = 0; i < size; ++i)
{
    cout << "nums[" << i << "] : " << nums[i]      << endl;
}

结果:

数[0] : 14

数量[1] : 6

数[2] : 4

数量[3] : 7

数量[4] : 8

数[5] : 1

数[6] : 4

谁能解释一下这个函数是如何工作的?我真的不明白你怎么能得到这些结果。谢谢!

最佳答案

这个逐行的描述可以让你知道行在做什么

//nums is an array of ints but is also the address of the 1st element in the array
int nums[] = { 9, 5, 4, 2, 8, 1, 3 };

// p is a  pointer to an int initialized to nums
// (initialized then to the address of the 1st e. in the array)
int *p = nums;

// p +2 means increase in the size of 2 integers the address of P
// meaning now, p points to the 3rd element
// *(p + 2) means I dereference that pointer and get the value of that address (4)
int tmp_num = *(p + 2);

// p gets now the address (&) of the 1st element of the array nums(the address of 9)
p = &nums[0];
// the value at that position is now added to the value of the next int 9+5,
// array is now:  { 14, 5, 4, 2, 8, 1, 3 };
*p = *p + *(p + 1);

// since p is a pointer p++ does increase by the size of one integer the address, 
// now p is pointing to element2 in the array ++p;
// dereference the pointer and now increase the value by 1. i.e. 5+1, 
   array is now:  { 14, 6, 4, 2, 8, 1, 3 };
++(*p);
// add 7 to element 4 of the array... new val is 7, array is now:  { 14, 6, 4, 7, 8, 1, 3 };
*(p + 2) = 7;
// p is now holding the address of the last element in the array
p = &nums[5] + 1;
// we set that value to 4, array is now:  { 14, 6, 4, 7, 8, 1, 4 };
*p = 4;

int size = sizeof nums / sizeof nums[0];
for (int i = 0; i < size; ++i)
{
    std::cout << "nums[" << i << "] : " << nums[i] << std::endl;
}

这只是因为你应该已经知道指针是什么,如何取消引用它以及如何设置它的值......

关于c++ - 我不明白的指针函数;(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712805/

相关文章:

c++ - 当将 int 转换为 int* 时会发生什么?

c++ - 有时为 const 的成员函数

c++ - 结构中引用的间接指针的意外地址,而不是使用普通变量的相同声明?

c++ - 无论枚举值的数量如何,枚举大小都是恒定的

C++:在点后提取字符串

c# - 如何使用 size_t 遍历 uint64*,c# 的等价物是什么?

c - 一个 friend 给我发了一段我不明白的片段。这是如何运作的?

c - 数组是按值传递还是按引用传递?

c++ - 本身就是模板的特化

c++ - 当返回类型是一个类时,指向返回值的指针的名称是什么?