Home>

I implemented a function mem_set that first allocates a memory area with malloc and then assigns v to the first n bytes of the object pointed to by the pointer p.
Then I wrote the following code to check the result.

for (int i = 0;i<n;i ++) {
    cout<<"xp ["<<i<<"] ="<<xp + i<<","<<* (xp + i)<<endl;
}
Error
  

warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]

  

'void *' is not a pointer-to-object type

The first warning is for xp + i and the second error is for: (xp + i).
What is a pointer to an object?
Is a general pointer like void * handled differently than a pointer like int *?

Source code
# include<iostream>
#include<cstdlib>
using namespace std;
void mem_set (void * p, int n, unsigned char v) {
    unsigned char * cp = (unsigned char *) p;
    while (n--) * cp ++ = v;
}
int main () {
    int n;
    cout<<"total index:";cin >>n;
    void * xp = malloc (sizeof (char) * n);
    mem_set (xp, n, 0);
    for (int i = 0;i<n;i ++) {
        cout<<"xp ["<<i<<"] ="<<xp + i<<","<<* (xp + i)<<endl;
    }
}
c
  • Answer # 1

      

    General pointers like void * are handled differently than pointers like int *

    void * has no target size, cast it to the required type (e.g. unsigned char *) and use it.

    [Appendix] ... Is it the intended result?

    usr ~/Project/test% ./a.out
    total index: 10
    xp [0] = AAAAAAAAAA, A
    xp [1] = AAAAAAAAA, A
    xp [2] = AAAAAAAA, A
    xp [3] = AAAAAAA, A
    xp [4] = AAAAAA, A
    xp [5] = AAAAA, A
    xp [6] = AAAA, A
    xp [7] = AAA, A
    xp [8] = AA, A
    xp [9] = A, A
    usr ~/Project/test% cat t1.cpp
    #include
    #include
    using namespace std;
    static void mem_set (unsigned char * p, size_t n, unsigned char v)
    {
        unsigned char * cp = p;
        while (n--) {
            * cp ++ = v;
        }
    }
    int main (void)
    {
        size_t n;
        cout<<"total index:";
        cin >>n;
        unsigned char * xp = new unsigned char [n];
        mem_set (xp, n, 'A');
        for (size_t i = 0;i

  • Answer # 2

    Nachchara * Adding int value: i to xp (xp + i) increases xp by sizeof (Nachara) The

    void * xp, that is, if the above "Nachara" is void
    Int value: When i is added (xp + i), xp increases by sizeof (void).

    However, since void is a "nothing" type, sizeof (void) has no meaning and will cause an error.

      

    'void *' is not a pointer-to-object type

    Because "void * is not a pointer to Nani", * (xp + i) has no meaning.

Trends