繁体   English   中英

打印函数中定义的指针的值和地址?

[英]Print value and address of pointer defined in function?

我认为这是一个非常容易编码的事情,但是我在 C 中的语法有问题,我刚刚用 C++ 编程。

#include <stdio.h>
#include <stdlib.h>

void pointerFuncA(int* iptr){
/*Print the value pointed to by iptr*/
printf("Value:  %x\n", &iptr );

/*Print the address pointed to by iptr*/

/*Print the address of iptr itself*/
}

int main(){

void pointerFuncA(int* iptr); 

return 0;
}

显然这段代码只是一个骨架,但我想知道如何在函数和主要工作之间进行通信,以及打印指向的地址和 iptr 本身的语法? 由于该函数是无效的,我如何将所有三个值发送到 main?

我认为地址是这样的:

printf("Address of iptr variable: %x\n", &iptr );

我知道这是一个简单的问题,但我在网上找到的所有示例都得到了值,但它在 main 中被定义为类似

int iptr = 0;

我需要创建一些任意值吗?

谢谢!

阅读评论

#include <stdio.h>
#include <stdlib.h>
    
void pointerFuncA(int* iptr){
  /*Print the value pointed to by iptr*/
  printf("Value:  %d\n", *iptr );
    
  /*Print the address pointed to by iptr*/
  printf("Value:  %p\n", iptr );

  /*Print the address of iptr itself*/
  printf("Value:  %p\n", &iptr );
}
    
int main(){
  int i = 1234; //Create a variable to get the address of
  int* foo = &i; //Get the address of the variable named i and pass it to the integer pointer named foo
  pointerFuncA(foo); //Pass foo to the function. See I removed void here because we are not declaring a function, but calling it.
   
  return 0;
}

输出:

Value:  1234
Value:  0xffe2ac6c
Value:  0xffe2ac44

要访问指针指向的值,您必须使用间接运算符*

要打印指针本身,只需访问指针变量而不使用运算符。

要获取指针变量的地址,请使用&运算符。

void pointerFuncA(int* iptr){
    /*Print the value pointed to by iptr*/
    printf("Value:  %x\n", *iptr );

    /*Print the address pointed to by iptr*/
    printf("Address of value: %p\n", (void*)iptr);

    /*Print the address of iptr itself*/
    printf("Address of iptr: %p\n", (void*)&iptr);
}

%p格式运算符要求相应的参数为void* ,因此有必要将指针强制转换为该类型。

int* iptr已经是一个指针了,所以写的时候不需要在它前面加&

printf("Address of iptr variable: %x\n", &iptr );

这是打印指针值的方法。

printf("Address of iptr variable: %p\n", (void*)iptr);

此外,您将pointerFuncA()的函数原型pointerFuncA()错误的位置,即在main() 在调用之前,它应该在任何函数之外。

#include <stdio.h>
#include <stdlib.h>

void pointerFuncA(int* iptr){
/*Print the value pointed to by iptr*/
printf("Value:  %p\n", (void*) iptr );

/*Print the address pointed to by iptr*/

/*Print the address of iptr itself*/
}

int main(){
int iptr = 0;
pointerFuncA( &iptr); 

return 0;
}

我想你正在看这样的东西,没有必要在 main 中再次重新定义函数....

地址是一些以 0x 开头的十六进制表示法写入的内存值

/指针 iptr 指向的值/

printf("Value is: %i", *iptr);

指针指向的地址将是 iptr 指针本身的值

/打印 iptr 指向的地址/

 printf("Address is: %p", iprt);

/打印 iptr 本身的地址/

 printf("Address of iptr: %p", &iptr )

暂无
暂无

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

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