3

我想知道 C 中这两个版本的 main() 代码有什么区别:

int main() {
   uint32_t a;
   f(&a);
}

int main() {
   uint32_t *a;
   f(a);
}

对于一个函数

void f(uint32_t *pointer) {
   // ...
}
4

4 回答 4

12

在您的第一个示例中,您将指针传递给 uninitialized variable af()例如,可以在那里存储一个值,并且main()以后可以使用该值。

在您的第二个示例中,您传递了一个未初始化的指针af()不能用它做任何有用的事情。

于 2013-10-07T21:11:05.627 回答
4

在第一个版本中,您将指向未初始化变量的指针传递给 f()。不要,除非 f() 的任务是初始化变量。

在第二个版本中,您将未初始化的指针传递给函数 f()。不。

于 2013-10-07T21:11:28.070 回答
2

他们定义了不同类型的变量,没有初始化。

uint32_t a; defines uint32_t variable on the stack and the function call will pass its address to the f() function.

uint32_t *a; defines a pointer on the stack and pass its value to the function. The pointer is not initialized, thus it could point to any block and any attempt to access that address will result into undefined behavior.

From the perspective of the f() function, it sees pointer values passed to it. In the first call, it can use that address, while in the second, it cannot.

于 2013-10-07T21:13:34.093 回答
2

wee pointer questions!!!

Ok so you know that the function f needs to take a pointer which is exactly as it sounds an address to that actual location in memory. For the first example(f(&a)) you have to pass the address because it lives inside the stack and really isn't shared anywhere outside the life of the function. so when the function returns the memory is destroyed and no longer available. the value of the pointer is not passed just the pointer to the value is passed. which can cause problems because if you change that value then all the things that "point to it" are now changed.

Now for the second one you get the memory from the heap or where ever but that stores the address of the value not the actual value so you can manipulate it and return nothing and the value is still there.

于 2013-10-07T21:13:34.167 回答