简体   繁体   English

C函数内部的指针

[英]Pointers inside function in C

#include<stdio.h>

int q = 10;

void fun(int *p){
    *p = 15;
    p = &q;
    printf("%d ",*p);
}    

int main(){
  int r = 20;
  int *p = &r;  
  fun(p);
  printf("%d", *p);
  return 0;
}

I was playing with pointers. 我在玩指针。 Could not understand the output of this. 无法理解此输出。 Output is coming as 10 15. Once p is pointing to address of q, why on returning to main function it's value changes? 输出为10 15.当p指向q的地址时,为什么返回主函数时其值会改变? Also why it changed to the value '15' which was assigned to it in the function before '10'. 也是为什么将其更改为在函数“ 10”之前为其分配的值“ 15”。

Because p is fun() is not the same p in main() . 因为pfun() ,所以main() p p , in each function, is local. 每个函数中的p是局部的。 So changing one doesn't affect other. 因此,更改一个不会影响其他。

In C, all function parameters are passed by value, including pointers. 在C语言中, 所有函数参数均按值传递,包括指针。

*p = 15; will set r to 15 as *p is pointing to the memory occupied by r in main() prior to its reassignment to &q ; 会将 r设置为15,因为*p指向main() r占用的内存,然后将其重新分配给&q

Your reassignment p = &q; 您的重新分配p = &q; does not change what p points to in the caller main() . 没有什么改变p于呼叫点main() To do that, you'd need to doubly indirect the pointer, ie change the function prototype to void fun(int **p){ , call it using fun(&p); 为此,您需要将指针间接加倍,即将函数原型更改为void fun(int **p){ ,然后使用fun(&p);对其进行调用fun(&p); , and reassign using *p = &q; ,然后使用*p = &q;重新分配 .

Two steps: 两步:

  1. First call to fun() , assigning the address of global int q [holding value 10] to p inside the fucntion scope and printing it. 首先调用fun() ,在函数作用域内的 p分配全局int q [保持值10]的地址并打印。 The first output ==> 10 ; 第一个输出==> 10 ;

  2. Once the call returns from fun() , it will hold the previous address, [passed from main() ] and hence, will print the value held by that address [which is 15 , modified inside fun() ]. 调用从fun()返回后,它将保留先前的地址[从main()传递],因此将打印该地址所保留的值[在fun()内部修改的值为15 ]。

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

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