c - 如何将整数指针传递给函数?

标签 c function pointers

在这里,我正在用 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);
}

有人可以指出是什么问题吗?另外,如何传递指向函数的指针?

最佳答案

您的错误是您将未初始化的整数指针传递给函数,然后使用了该指针。您可能打算做的是在堆栈上自动分配一个整数,然后将所述整数的地址传递给函数。

#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);
}

关键是要记住,当您这样做时int *c您正在分配一个指针,当您这样做时 int c您正在分配一个整数。如果你想修改传递给函数的变量,C 中的典型模式是传递所述变量的地址,但首先需要分配正确的类型,在这种情况下是 int而不是 int * .然后您可以使用运营商的地址 &获取相关数据的地址,然后将其作为函数参数传递。

关于c - 如何将整数指针传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31714475/

相关文章:

php - 比较 PHP 中的字符串,如果它们相似,则从数组中删除其中一个

c# - 存储指向方法参数的指针以供以后重用

c - 这段代码在做我想做的事吗?

c - 如何评估C中的输入数据?

arrays - Powershell 2 : Array size differs between return value and caller

swift - 在 NavigationView 中使用函数会引发错误 : Cannot convert return expression of type 'AnyView.Type' to return type 'AnyView'

c - (C) 传递给 func 的指针与原始指针不同

c - 带空指针的动态数组

即使 IF 语句为 false,字符指针数组也会被覆盖

c - 从字符串中删除一个字符