gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:06:11 25 4
gpt4 key购买 nike

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

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/

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