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

Jongware
  • 22,200
  • 8
  • 54
  • 100
Rushabh
  • 651
  • 5
  • 15

1 Answers1

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());
}
Matt
  • 7,100
  • 3
  • 28
  • 58
  • `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) – M.M Apr 20 '14 at 05:57
  • Also, `while(i)` will always be true and you will run off the end of your array and into la-la land – M.M Apr 20 '14 at 05:58
  • 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. – Matt Apr 20 '14 at 14:10
  • 1
    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 . – M.M Apr 20 '14 at 14:43