Pra*_* Cm 2 c pointers function
这里我在C中执行一个简单的代码.它正在编译很好但在运行时陷阱.
#include <stdio.h>
#include <conio.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
void main()
{
int a=10,b=20,*c;
sum(a,b,c);
printf("sum is %d\n",*c);
}
Run Code Online (Sandbox Code Playgroud)
有人可以指出问题是什么吗?另外,如何将指针传递给函数?
您的错误是您已将未初始化的整数指针传递给函数,然后使用指针.你可能想要做的是自动在堆栈上分配一个整数,然后将所述整数的地址传递给函数.
#include <stdio.h>
#include <conio.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
void main()
{
int a=10,b=20,c; // Automatically allocate an integer on the stack
sum(a,b,&c); // Third argument is the address of the integer
printf("sum is %d\n",c);
}
Run Code Online (Sandbox Code Playgroud)
关键是要记住,当你这样做时,int *c
你正在分配一个指针,当你这样做时,int c
你正在分配一个整数.如果你想修改传递给函数的变量,C中的典型模式是传递所述变量的地址,但首先需要分配正确的类型,在这种情况下是一个int
而不是一个int *
.然后,您可以使用运算符的地址&
来获取相关数据的地址,然后将其作为函数参数传递.
上面程序中的问题是未初始化的指针c
。所以你可以分配内存c
使用malloc
-
#include <stdio.h>
#include <stdlib.h>
void sum(int x,int y,int *z)
{
*z=x+y;
}
int main() // declare main as int.
{
int a=10,b=20,*c;
c=malloc(sizeof(int)); //allocating memory to pointer c
sum(a,b,c);
printf("sum is %d\n",*c);
free(c); // freeing allocated memory
retrirn 0;
}
Run Code Online (Sandbox Code Playgroud)