简体   繁体   English

有没有办法取消引用 C 中的空指针?

[英]Is there a way to dereference a void pointer in C?

The calloc function in C returns a void pointer but the memory bytes pointed to are already initialized with values, How is this is achieved? C 中的calloc function 返回一个void 指针,但指向的 memory 字节已经用值初始化,这是如何实现的?

I am trying to write a custom calloc function in C but can't find a way to initialize the allocated memory bytes我正在尝试在 C 中编写自定义 calloc function 但无法找到初始化分配的 memory 字节的方法

My code我的代码

#include "main.h"

/**
 * _calloc - Allocate memory for an array
 * @nmemb: Number of elements
 * @size: Size of each element
 *
 * Description: Initialize the memory bytes to 0.
 *
 * Return: a Void pointer to the allocated memory, if error return NULL
 */
void *_calloc(unsigned int nmemb, unsigned int size)
{
        unsigned int i, nb;
        void *ptr;

        if (nmemb == 0 || size == 0)
                return NULL;

        nb = nmemb * size;

        ptr = malloc(nb);

        if (ptr == NULL)
                return NULL;

        i = 0;
        while (nb--)
        {
/*How do i initialize the memory bytes?*/
                *(ptr + i) = '';
                i++;
        }

        return (ptr);
}

Simply use pointer to another type to dereference it.只需使用指向另一种类型的指针来取消引用它。

example:例子:

void *mycalloc(const size_t size, const unsigned char val)
{
    unsigned char *ptr = malloc(size);
    if(ptr) 
        for(size_t index = 0; index < size; index++) ptr[index] = val;
    return ptr;
}

or your version:或者你的版本:

//use the correct type for sizes and indexes (size_t)
//try to have only one return point from the function
//do not use '_' as a first character of the identifier 
void *mycalloc(const size_t nmemb, const size_t size)
{
    size_t i, nb;
    char *ptr = NULL;

    if (nmemb && size)
    {
        nb = nmemb * size;
        ptr = malloc(nb);
        if(ptr)
        {
            i = 0;
            while (nb--)
            {
                    //*(ptr + i) = 'z';
                    ptr[i] = 'z';  // isn't it looking better that the pointer version?
                    i++;
            }
        }
    }
    return ptr;
}

Then you can use it assigning to other pointer type or casting.然后你可以使用它分配给其他指针类型或转换。

example:例子:

void printByteAtIndex(const void *ptr, size_t index)
{
    const unsigned char *ucptr = ptr;

    printf("%hhu\n", ucptr[index]);
}

void printByteAtIndex1(const void *ptr, size_t index)
{
 
    printf("%hhu\n", ((const unsigned char *)ptr)[index]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM