简体   繁体   English

赋值从指针进行整数运算而无需强制转换

[英]assignment makes integer from pointer without a cast

struct libimg 
{
   Elf32_Phdr ph;
};

struct libimg limg = {
   {
      p_type: PT_LOAD,
      p_memsz: 2 * PAGE_SIZE
   }
};

static void makelib(void *r)
{
    limg.ph.p_vaddr = r;
}

And Elf32_Phdr is defined in linux/elf.h Elf32_Phdrlinux/elf.h定义

typedef struct elf32_phdr{
   Elf32_Addr    p_vaddr;
   ....
 } Elf32_Phdr;

I want to assign p_vaddr value from the argument. 我想从参数中分配p_vaddr值。 But I get this warning assignment makes integer from pointer without a cast . 但是我得到了这个警告assignment makes integer from pointer without a cast I use gdb to check and print r shows (void *)0x08040000 我使用gdb检查并print r显示(void *)0x08040000

The compiler is warning you that an assignment caused an implicit cast. 编译器警告您分配导致了隐式强制转换。 It does so because that might have been unintentional, and could potentially have undesirable effects. 这样做是因为这可能是无意的,并可能产生不良影响。 You could rectify that by using the correct type in the first place: 您可以首先使用正确的类型来纠正此问题:

static void makelib(Elf32_Addr r)
{
    limg.ph.p_vaddr = r;
}

That might cause other code lines to generate warnings, and you should use a cast in these places, for example: 这可能会导致其他代码行生成警告,因此您应该在以下位置使用强制转换,例如:

makelib((Elf32_Addr)someVariable);

The idea is to cast at the place where you change the meaning of a value from type A to type B, where it's a concise, deliberate decision. 这个想法是在将值的含义从类型A更改为类型B的地方进行的,这是一个简洁,刻意的决定。 You should only do that (casting) if you can't use the proper type in the first place, that is, if someVariable can't be Elf32_Addr . 仅当您不能首先使用正确的类型(即someVariable不能为Elf32_Addr )时,才应该这样做(广播)。

In Linux/arch/powerpc/boot/elf.h Linux / arch / powerpc / boot / elf.h中

 94 typedef struct elf32_phdr {
 95         Elf32_Word p_type;
 96         Elf32_Off p_offset;
 97         Elf32_Addr p_vaddr;
 98         Elf32_Addr p_paddr;
 99         Elf32_Word p_filesz;
100         Elf32_Word p_memsz;
101         Elf32_Word p_flags;
102         Elf32_Word p_align;
103 } Elf32_Phdr;

Where Elf32_Addr 哪里Elf32_Addr

typedef unsigned int Elf32_Addr;

Finally you are assigning a void * to a unsigned int 最后,您将void *分配给unsigned int

Cast it as unsigned int or better to Elf32_Addr to avoid warning: 将其转换为Elf32_Addr unsigned int或更好的形式转换为Elf32_Addr以避免警告:

limg.ph.p_vaddr = (Elf32_Addr)r;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM