Вопрос

  • Platform: Linux 3.2.0 x86 (Debian Wheezy)
  • Compiler: GCC 4.7.2 (Debian 4.7.2-5)

I am writing some functions similar to memset(), memcpy(), etc. in string.h. I use void pointers to avoid making the functions type specific. But I do not know why I ask for a void pointer when I use a char pointer to dereference the void pointer. It seems to me that the void pointer does not do anything. So my question is what does a void pointer do? For an example here is one of my functions.

size_t damlocs(size_t sizele, void *val, size_t valsiz, void *ele, size_t elesiz)
{
            //All that 'ele' is used for is this assignment
    char *elebyt = ele;
    char *valbyt = val;
    size_t eleind = 0;
    size_t elebytind = 0;
    size_t valbytind = 0;

    if(elebyt && valbyt)
    {
        while(eleind++ < elesiz)
        {
            elebytind = eleind * sizele;
            valbytind = 0;

            while(elebyt[elebytind++] == valbyt[valbytind++])
                if((valbytind + 1) / sizele == valsiz)
                    return eleind + 1;
        }
    }

    return 0;
}

Description: damlocs() will locate the sequence pointed to by 'val' within 'ele[0]' to 'ele[elesiz - 1]' and return the element at which the beginning of the sequence was found. If the sequence is not found zero will be returned. It is similar in concept to bsearch() declared in stdlib.h but a byte to byte comparison is used instead.

Это было полезно?

Решение

In C, all object pointers are implicitly convertible to and from void pointers, so you can easily call your function with (&x, sizeof x) for any object x.

It's true that you would use some kind of char pointer to address memory as an array of bytes, but if your function took a char *, you would need an explicit cast at the call site.

Другие советы

Void pointer additionaly tells the programmer:

method takes a pointer to a block of memory containing anything

We could make char* implicitly convertible, but that would create a lot of confusion (and bugs caused by not so careful coders).

If I'm understanding this right then its basically like the other two answers said. In essence a void pointer just generates a pointer to set of memory and can be cast to any other type of pointer.

Basically, you need to cast to other pointer types that way pointer arithmetic works correctly for addressing particular data types in the allocated memory.

For example, in your case you use a character pointer as you stated:

char *elebyt = ele; char *valbyt = val;

So in this case when you increment the pointer I.E.

eleind++

you are going to add 1 byte to the pointer, rather than the size of an integer (usually 8 bytes)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top