0

可能重复:
设置 void * 指针等于一个整数

我之前的问题已经结束了,可能我没有说清楚,我可以再问一次吗?

我有一个指针:

void * p;
p = malloc(sizeof(int));

然后有一个int:

int age = 20;
p = (void*)age;

我的问题是如何p = (void*)age;工作?如果 p 是一个指针,那么 (void*) 前面的作用是age什么?为什么值为p20?

4

4 回答 4

3

You are creating an automatic variable called age and you are also creating a variable called p which is a void * pointer. This means it is a pointer to something, but you do not know what. You are then assigning the value of age to the pointer p. In order to satisfy the type system you have to cast it to void * by using the (void *) syntax in order to say to the compiler "I know what I am doing.".

As for the reason why you are storing an integer in a void * pointer... there is no good reason I can think of. Perhaps you meant p = &age, which means p points to the variable on the stack.

To answer ratzip's comment:

`(void *)age`

Means "a void * pointer with the value of age".

If I wrote void *p = malloc(1) then it would allocate some memory and the numerical value of p would be the address in memory, for example 12345. If I went to that value in memory I would find the memory I allocated. If I write (void *)age then I am casting (i.e. taking the value in one type and storing in a different type) and assigning it to p. So the value of p is 20, p points to "memory at address 20". Which is meaningless unless you know that there is some memory there that you want to use. I can say with 99.999% certainty that this is not the case. int and pointer are both numbers, but they are used for very different purposes. One represents a number to the user, one represents a memory address to the computer.

(Of course with virtualised memory the above is not strictly true)

于 2012-08-20T13:38:25.850 回答
1

强制转换使编译器假设您知道自己在做什么,并发出将整数值age转换为地址的代码。这通常不是很难,因为无论如何地址只是整数值。

当然,20用作地址是非常不明智的,因此如果指针被取消引用,这段代码可能会导致崩溃。

文本(void *)是括在括号中的类型名称,这在 C 中称为“强制转换”,它用于将其后面的表达式的类型转换为命名类型。通常,看到涉及的强制转换void *应该作为一个警告信号,因为在正确的代码中很少需要它们。

于 2012-08-20T13:36:11.453 回答
0

The (void*) is a type cast and is casting the integer value of 20 to a (void*) value of 20.

Basically, you are setting your current (void*) value returned from malloc() to 0x00000014.

If you are trying to set p to the address of the age integer, you need to do this:

p = &age;

If you want to fill in the memory pointed to by p (that you allocated with malloc) with a value of 20, then you need to do this:

*p = age;
于 2012-08-20T13:38:34.090 回答
0

当您将和整数转换为指针然后将其放入时,p明确指定指向的地址p20

通常,您不知道您使用的数据的显式地址,因此使用&运算符或一些内存管理工具(如malloc.

但是,这种用例在嵌入式系统领域非常普遍。通常,硬件有一组映射到地址空间的寄存器,像下面这样的结构非常常见。所有这些地址都在硬件文档中指定。

#define SOME_DEVICE_REG_ADDRESS 0x10050000
...
uint32_t *p = (uint32_t *)SOME_DEVICE_REG_ADDRESS
于 2012-08-20T13:45:00.583 回答