如何创建一个将 10 个字节分配给指针的函数,然后检查指针是否已分配,return 布尔值?

How to create a function that alloccate 10 bytes to a pointer, then check whether pointer has been allocated yet, return boolean?

抱歉我的英语不好。我现在正在从根学习C编程,我有作业。

问题是:创建一个动态分配10个字节给指针的函数,然后检查指针是否已经分配?该函数必须是布尔值,并且 return 也是布尔值。

函数原型:bool allocate10Bytes(uint8_t * outPtr);

请帮我解决这个问题。非常感谢!

你的意思好像是下面这样

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>

bool allocate10Bytes( uint8_t **outPtr )
{
    const size_t N = 10;

    *outPtr = malloc( N * sizeof( uint8_t ) );

    return *outPtr != NULL;
}

int main(void) 
{
    uint8_t *p;

    bool success = allocate10Bytes( &p );

    if ( success ) free( p );

    return 0;
}

你问题中的这个函数原型

bool allocate10Bytes(uint8_t * outPtr);

无效。要成为输出参数,指针必须声明为 uint8_t **outPtr。那是一个参数(某个指针)应通过指向该指针的指针通过引用传递。

注意:如果您试图将程序编译为 C++ 程序,那么至少重写此语句

*outPtr = malloc( N * sizeof( uint8_t ) );

喜欢

*outPtr = ( uint8_t * )malloc( N * sizeof( uint8_t ) );

并删除 header <stdbool.h>