简体   繁体   English

函数中的双指针解引用

[英]Double pointer dereferences in a function

I'm trying to understand double pointers. 我正在尝试理解双指针。 I think i should be able to write (**min = 3;) in the MinMax loop below, but it is just ignored. 我认为我应该能够在下面的MinMax循环中写入(** min = 3;),但是它只是被忽略了。 I think it should set the value pointed to by the value of min (pointer to start) to 3 (or of course to any int). 我认为应该将min(指向起点的指针)的值所指向的值设置为3(当然也可以是任何int值)。 Can someone help me understand why this is crazy talk? 有人可以帮助我理解为什么这是疯狂的谈话吗? There is no reason in the function to set this value of course, i just want to understand why it doesn't work. 函数中没有理由设置该值,我只是想了解为什么它不起作用。

int ar[] = {1,23,4,32,5,67,999,-1};
int *min= 0;
int *max= 0;
MinMax(ar,ar+8,&min,&max);

void MinMax(int *start,int *end, int **min,int **max) {
  // **min = 3; //why not?
  *min = start; 
  *max = start;
  while(++start < end) {
  if(*start < **min) *min = start;
  if(*start > **max) *max = start;
  }
}

At the point you have **min = 3 the value of *min is 0, ie a NULL pointer, which means it doesn't point anywhere. 在您拥有**min = 3的点上, *min值为0,即NULL指针,这意味着它没有指向任何地方。 Attempting to dereference *min and subsequently write to it invokes undefined behavior . 尝试取消引用*min并随后对其进行写入会调用未定义的行为

The following lines set both *min and *max to point to the same place as start , so after that they can be dereferenced. 以下各行将*min*max都设置为与start指向同一位置,因此之后可以将其取消引用。

On entering the function *min is zero so **min = 3 is setting an integer at address zero to three. 输入函数* min为零,因此** min = 3会将地址0处的整数设置为3。 Not normally allowed at run time. 通常在运行时不允许。 It is only after initialising *min to a valid address, for example *min = start, that you can then set **min to a value. 只有在将* min初始化为有效地址(例如* min = start)之后,才可以将** min设置为一个值。

void MinMax(int *start,int *end, int **min,int **max) {
    // **min = 3;

You start with initializing your function's argument to point to null so **min is not a defined value ( *min is null but dereferencing a null pointer is UB.) To make **min a valid object, first set *min to point to a valid object, for instance 从初始化函数的参数以指向null开始,所以**min不是一个定义的值( *min为空,但取消引用空指针为UB。)若要使**min为有效对象,请首先将*min设置为指向一个有效的对象,例如

int *min = malloc(sizeof(int));

(don't forget to deallocate it later) or (不要忘了以后再分配它)或

int m = 0;
int *min = &m;

or even 甚至

int *min = ar;

(thought that latter is already performed in MinMax .) (认为​​后者已经在MinMax执行了。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM