抱歉我的英语不好。我现在正在从根本上学习C编程,并且我有一个作业。
问题是:创建一个函数,动态分配10个字节给指针,然后检查指针是否已分配?该函数必须是 boolean 值,并且也返回 boolean 值。
函数原型(prototype):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;
}
您问题中的这个函数原型(prototype)
bool allocate10Bytes(uint8_t * outPtr);
无效。要成为输出参数,指针必须声明为 uint8_t **outPtr
。这是一个参数(某个指针)应通过指向该指针的指针通过引用传递。
注意:如果您尝试将程序编译为 C++ 程序,那么至少重写此语句
*outPtr = malloc( N * sizeof( uint8_t ) );
喜欢
*outPtr = ( uint8_t * )malloc( N * sizeof( uint8_t ) );
并删除标题 <stdbool.h>
关于c - 如何创建一个函数,为指针分配10个字节,然后检查指针是否已分配,返回 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57166868/