Home > Enterprise >  How to get/print the name/identifier of an array in C ?
How to get/print the name/identifier of an array in C ?

Time:04-16

I have a function and I want to print the name/identifier of the array I pass as an argument.

void printArrayElements(int num[], int size){
 cout << "Array name: " << num << endl;
for(int i=0;i<size;i  ){
    cout << "Array elements: " << num[i] << endl;
}
cout << endl;
}

When I pass (test,5) and (cool,10) as an argument,

int main(){

int test[5] = {1,2,3,4,5};
int cool[10] = {4,1,2,4,5,3,7,4,2,7};
printArrayElements(test,5);
printArrayElements(cool,10);

}

The result I get is,

Terminal Image: https://i.stack.imgur.com/2jEtc.png

I want the name of the array cool and jess to be printed after "Array name:" not 0x61ff0c and 0x61fee4.

cout << "Array name: " << num << endl;

By this, I intend to print the identifier of the array passed into the function as an argument. Its not working. How do I make that happen?

CodePudding user response:

You can wrap the function in a macro, and use the preprocessor to get the variable name as a string.

#include <iostream>
#include <string>

#define printArray(x, y) printArrayElements((#x), x, y)

void printArrayElements(std::string name, int num[], int size){
    std::cout << "Array name: " << name << std::endl;
    for(int i=0;i<size;i  ){
        std::cout << "Array elements: " << num[i] << std::endl;
    }
    std::cout << std::endl;
}

int main() {
    int test[5] = {1,2,3,4,5};
    int cool[10] = {4,1,2,4,5,3,7,4,2,7};

    printArray(test, 5);
    printArray(cool, 10);
}

CodePudding user response:

This is not possible with vanilla C at the moment, but you can use the preprocesser to do it:

#define PRINTNAME(name) (std::cout << "name" << ":" << (#name) << std::endl)
  •  Tags:  
  • c
  • Related