vendredi 1 juillet 2016

Alternative notation to *(ptr)[j++]?

When passing a double pointer to a function, I used the notation *ptr[j++] in my function which lead the program to crash. I guessed it happened due to operator precedence, so I rectified it by writing (*ptr)[j++] but I didn't like this notation. It feels long and confusing.

I also know of the notation ptr[0][j++] but I also don't like it.Is there any better notation or approach around all of this?

My code:

#include <iostream>

using namespace std;

void mset(int **ptr, size_t size);

void main(void)
{
    const size_t size = 10;
    int *ptr = new int[size];
    mset(&ptr, size);
    for (size_t n = 0; n < size; n++) {
        std::cout << ptr[n] << std::endl;
    }
}

void mset(int **ptr, size_t size)
{
    size_t j = 0;
    while(j < size)
        (*ptr)[j++] = 3;
}

P.S I know that I can write void mset(int *ptr, size_t size) and invoke mset(ptr, size), but I am asking about that particular case.

Aucun commentaire:

Enregistrer un commentaire