Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the variable name passed to a function in C

Tags:

c

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.

like image 942
BhavinT Avatar asked Sep 17 '25 05:09

BhavinT


2 Answers

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;
}
like image 97
Jonathon Reinhart Avatar answered Sep 19 '25 20:09

Jonathon Reinhart


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);
}
like image 27
Eric Postpischil Avatar answered Sep 19 '25 19:09

Eric Postpischil