malloc指针地址在main和其他函数中的区别 [英] malloc pointer address in main and in other function difference

查看:128
本文介绍了malloc指针地址在main和其他函数中的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.在下面的示例中,为什么两个指针的地址有所不同?这是完整的代码:

I have the following question. Why is there a difference in the addresses of the two pointers in following example? This is the full code:

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

void *mymalloc(size_t bytes){
void * ptr = malloc(bytes);
printf("Address1 = %zx\n",(size_t)&ptr);
return ptr;
}

void main (void)
{
unsigned char *bitv =  mymalloc(5);
printf("Address2 = %zx\n",(size_t)&bitv);
}

结果:

Address1 = 7ffe150307f0
Address2 = 7ffe15030810

推荐答案

这是因为您正在打印指针变量的地址,而不是指针的地址.从打印文件中的bitvptr中删除与号(&).

It's because you are printing the address of the pointer variable, not the pointer. Remove the ampersand (&) from bitv and ptr in your printfs.

printf("Address1 = %zx\n",(size_t)ptr);

printf("Address2 = %zx\n",(size_t)bitv);

另外,将%p用作指针(然后不要转换为size_t)

Also, use %p for pointers (and then don't cast to size_t)

为什么?

在这一行代码中:

 unsigned char *bitv =  mymalloc(5);

bitv是一个指针,其值是新分配的内存块的地址.但是该地址也需要存储,而&bitv是该值的存储地址.如果您有两个存储相同指针的变量,则它们仍将各自拥有自己的地址,这就是&ptr&bitv具有不同值的原因.

bitv is a pointer and its value is the address of the newly allocated block of memory. But that address also needs to be stored, and &bitv is the address of the where that value is stored. If you have two variables storing the same pointer, they will still each have their own address, which is why &ptr and &bitv have different values.

但是,正如您所期望的,当您更改代码时,ptrbitv将具有相同的值.

But, as you expected, ptr and bitv will have the same value when you change your code.

这篇关于malloc指针地址在main和其他函数中的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆