C編程:malloc()在另一個函數中我需要幫助malloc() 在另一個函數中.我經過一個指針和大小從我的main()我想為這個指針動態地分配內存malloc()但我看到的是.正在分配的內存用于在我調用的函數中聲明的指針,而不是用于在main().如何將指針傳遞給函數并為傳遞的指針分配內存從調用函數內部?我編寫了以下代碼,并得到如下所示的輸出。資料來源:int main(){
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(input_image, bmp_image_size)==NULL)
printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
else
printf("\nPoint3: Memory not allocated");
return 0;}signed char alloc_pixels(unsigned char *ptr, unsigned int size){
signed char status = NO_ERROR;
ptr = NULL;
ptr = (unsigned char*)malloc(size);
if(ptr== NULL)
{
status = ERROR;
free(ptr);
printf("\nERROR: Memory allocation did not complete successfully!");
}
printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));
return status;}程序輸出:Point1: Memory allocated ptr: 262144 bytesPoint2: Memory allocated input_image: 0 bytes
3 回答
BIG陽
TA貢獻1859條經驗 獲得超6個贊
int main(){
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
else
printf("\nPoint3: Memory not allocated");
return 0;}signed char alloc_pixels(unsigned char **ptr, unsigned int size) {
signed char status = NO_ERROR;
*ptr = NULL;
*ptr = (unsigned char*)malloc(size);
if(*ptr== NULL)
{
status = ERROR;
free(*ptr); /* this line is completely redundant */
printf("\nERROR: Memory allocation did not complete successfully!");
}
printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr));
return status; }
慕田峪9158850
TA貢獻1794條經驗 獲得超8個贊
如何將指針傳遞到函數并從調用函數內部為傳遞的指針分配內存?
int
int foo(void){
return 42;}int*int):
void foo(int* out){
assert(out != NULL);
*out = 42;}T*
T* foo(void){
T* p = malloc(...);
return p;}void foo(T** out){
assert(out != NULL);
*out = malloc(...);}
aluckdog
TA貢獻1847條經驗 獲得超7個贊
void allocate_memory(char **ptr, size_t size) {
void *memory = malloc(size);
if (memory == NULL) {
// ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
}
*ptr = (char *)memory;}int main() {
char *data;
allocate_memory(&data, 16);}- 3 回答
- 0 關注
- 809 瀏覽
添加回答
舉報
0/150
提交
取消
