有没有一种方法可以取消引用C中的空指针



C中的calloc函数返回一个空指针,但指向的内存字节已经用值初始化,这是如何实现的?

我正在尝试用C编写一个自定义calloc函数,但找不到初始化分配的内存字节的方法

我的代码

#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);
}

只需使用指向另一个类型的指针来取消引用它。

示例:

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;
}

或您的版本:

//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;
}

然后您可以使用它来分配给其他指针类型或强制转换。

示例:

void printByteAtIndex(const void *ptr, size_t index)
{
const unsigned char *ucptr = ptr;
printf("%hhun", ucptr[index]);
}
void printByteAtIndex1(const void *ptr, size_t index)
{

printf("%hhun", ((const unsigned char *)ptr)[index]);
}