[英]passing a pointer as argument to a function in C
Something I stumbled upon and made me wonder. 我偶然发现的东西使我感到奇怪。 Why does this work?
为什么这样做?
void foo (int* a)
{
int x = 3;
*a = x;
}
int main()
{
int a;
foo(&a);
return 0;
}
But this causes a segmentation fault (both on Visual Studio 2008 and gcc)? 但这会导致分段错误(在Visual Studio 2008和gcc上)?
void foo (int* a)
{
int x = 3;
*a = x;
}
int main()
{
int* a;
foo(a);
return 0;
}
Is it something defined in the language or just an implementation issue? 它是用语言定义的还是只是实现问题?
When you declare 当你声明
int* a;
You are declaring a pointer variable a
but you are not making it point to anything. 您在声明一个指针变量
a
但没有使它指向任何东西。 Then in the function, you do 然后在函数中,
*a = x;
Which dereferences the pointer and tries to assign what it points to the value of x
. 它取消引用指针,并尝试将其指向
x
的值。 But since it doesn't point to anything, you get undefined behaviour, manifested in a segmentation fault. 但是由于它没有指向任何内容,因此您会得到不确定的行为,表现为分段错误。
You should do this: 你应该做这个:
int i; // the actual integer variable
int* a = &i; // a points to i
The difference between that and the first one is that int a;
那和第一个之间的区别是
int a;
declares a real integer variable, then you take its address with &a
and passes it to the function. 声明一个实数整数变量,然后使用
&a
获取其地址,并将其传递给函数。 The pointer a
inside the function foo
points to the variable a
in main
, and so dereferencing it and assigning to it is perfectly fine. 函数
foo
内部的指针a
指向main
的变量a
,因此取消引用并将其赋值是完全可以的。
int a;
Assigns memory as soon as you declare it but this not the case with int *a; 声明后立即分配内存,但int * a则不是这种情况;
int *a;
is pointer declaration (MEMORY not yet allocated for that). 是指针声明(尚未为此分配内存)。
int *a = (int*)malloc(sizeof(int)); // allocate memory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.