I am writing a demo program to print address of the variable. To make the code look cleaner I have created a header file in which the function is declared(ex.pointer.h) and a C file for calling that function(ex. main.c). I want to print the address of the variable with the variable name called in main.c
main.c:
#include "pointer.h"
int main(int argc, char *argv[]){
int var=40;
printAddress(var);
}
pointer.h
#include<stdio.h>
int *p;
#define getName(var) #var
void printAddress(int a){
p=&a;
printf("Address of variable %s is %p\n",getName(a),p);
}
I tried using macros but it printsAddress of variable a is 0x7fff2424407c
which is not the expected outputAddress of variable var is 0x7fff2424407c
. Can anyone please tell me what changes I should make and please explain.
You can't print the address of a variable using function like you've shown. The reason is that a
is local variable, which has a different identity than the variable whose value you passed to printAddress
.
You also can't get the name, because the name doesn't exist in that context.
However, you could use a macro:
#define printAddress(x) printf("Address of variable %s is %p\n", #x, &x)
Note that #
here is the stringification operator of the preprocessor; it turns a token into a C string literal (effectively just adding quotes around the token).
Full example:
#include <stdio.h>
#define printAddress(x) printf("Address of variable %s is %p\n", #x, &x)
int main(void)
{
int foo;
printAddress(foo);
return 0;
}
A macro can prepare the name and address of a variable before passing it to the actual function. Do not do this in production code:
#include <stdio.h>
void printAddress(char *name, void *address)
{
printf("The address of %s is %p.\n", name, address);
}
#define printAddress(x) printAddress(#x, &(x))
int main(void)
{
int var = 40;
printAddress(var);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With