我认为这是一个很容易编码的东西,但我在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;
}
Run Code Online (Sandbox Code Playgroud)
显然这段代码只是一个骨架,但我想知道如何在函数和主要工作之间进行通信,以及打印指向的地址和iptr本身的语法?由于函数无效,如何将所有三个值发送到main?
我认为地址是这样的:
printf("Address of iptr variable: %x\n", &iptr );
Run Code Online (Sandbox Code Playgroud)
我知道这是一个简单的问题,但我在网上发现的所有例子都得到了价值,但它在主要定义为
int iptr = 0;
Run Code Online (Sandbox Code Playgroud)
我需要创建一些任意值吗?
谢谢!
Ata*_*car 15
阅读评论
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Value: 1234
Value: 0xffe2ac6c
Value: 0xffe2ac44
Run Code Online (Sandbox Code Playgroud)
要访问指针指向的值,必须使用间接运算符*.
要打印指针本身,只需访问没有运算符的指针变量.
要获取指针变量的地址,请使用&运算符.
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);
}
Run Code Online (Sandbox Code Playgroud)
该%p格式的操作需要相应的说法是void*,这样的三分球投射到这种类型的有必要.