简体   繁体   中英

Print an Array in C++ using void pointer

I am building a DirectX game, in which I have a Debug::Log static function defined in the Debug class. This just prints the values of the passed parameter on the output/console. I want to implement a function where I can pass a starting pointer to the array(that I want to print), and print all elements in the array. However I want to let the function be flexible with the type of params passed. So, I am doing something like this..

static void DebugArray(void* pointerToArray) {
    std::stringstream ss;
    ss << "\n";

    void *i = pointerToArray;
    int k = 0;
    while(i) {
        ss << i; //This is how I am storing the array's elements
        i++; //Error in VS 2012 expression must be a pointer to a complete object type  

    }
    print(ss.str());
}

Is this is valid way of doing the intended work? How should I approach this? Any suggestions

Type needs to be known at compile time, so you'll need to use a template instead.

template <class T>
static void DebugArray(T* pointerToArray) {
    std::stringstream ss;
    ss << "\n";

    T *i = pointerToArray;
    int k = 0;
    while(i) {
        ss << *i; //This is how I am storing the array's elements
        i++; //Error in VS 2012 expression must be a pointer to a complete object type  

    }
    print(ss.str());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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