1

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

3
  • 1
    See the accepted answer to this question: Void pointer arithmetic Commented Apr 19, 2014 at 23:18
  • 1
    Unless you are always dealing with strings, won't this just overflow and segfault? Commented Apr 19, 2014 at 23:24
  • Can you give an example of how the array data is set up and how you call this function? Commented Apr 20, 2014 at 5:59

1 Answer 1

2

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());
}
Sign up to request clarification or add additional context in comments.

4 Comments

ss << i just stores the pointer value. It does not access the objects being pointed-to (unless T is char ; std::ostream has an overload for char which reads a string from the pointed-to space)
Also, while(i) will always be true and you will run off the end of your array and into la-la land
Thanks @mattmcnabb, added dereference of the array element. It's always possible that the array referred to is null terminated. I just modified the ops code to work as they'd written it. They need to figure out how to stop price ting elements.
Even if the array is null-terminated, while(i) never terminates , incrementing a non-null pointer never makes it null. You could try while(*i) but we don't know if T has a conversion to bool. Hopefully OP can clarify .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.