在 C 语言中将指针传递给函数

如何编写一个 C 程序来将指针传递给函数?或者,在 C 语言编程中,指向函数的指针是如何通过一个实际例子来工作的。

在 C 语言中将指针传递给函数的示例

在这个将指针传递给函数的程序中,我们创建了一个函数,它接受两个整型变量并交换这两个变量。我建议您参考“交换两个数的 C 程序”这篇文章来理解其逻辑。

与任何其他变量一样,您可以将指针作为函数参数传递。我建议您参考“值传递和引用传递”“指针”这两篇文章来理解 C 语言的函数参数和指针。

#include<stdio.h>
 
void Swap(int *x, int *y)
{
    int Temp;
    Temp = *x;
    *x = *y;
    *y = Temp;
}

int main()
{
    int a, b;
    
    printf ("Please Enter 2 Integer Values :  ");
    scanf("%d %d", &a, &b);
    
    printf("\nBefore Swapping  A = %d and B = %d", a, b);
    
    Swap(&a, &b);
    
    printf(" \nAfter Swapping   A = %d and B = %d \n", a, b);
}
Pass Pointers to Functions Example

将指针传递给函数的示例 2

在这个将指针传递给函数的程序中,我们创建了一个接受数组指针及其大小的函数。请参考“计算数组中所有元素之和的 C 程序”这篇文章来了解其逻辑。在主程序“将指针传递给函数”中,我们使用 for 循环来遍历数组。接下来,将用户给定的值传递给一个数组。然后,我们将一个数组传递给一个函数。

#include<stdio.h>
 
int SumofArrNumbers(int *arr, int Size)
{
    int sum = 0;
    for(int i = 0; i < Size; i++)
    {
        sum = sum + arr[i];
    }
    return sum;
}
int main()
{
    int i, Addition, Size, a[10];
    printf("Please Enter the Size of an Array : ");
    scanf("%d", &Size);
    
    printf("\nPlease Enter Array Elements  :  ");
    for(i = 0; i < Size; i++)
    {
        scanf("%d", &a[i]);
    }
    
    Addition = SumofArrNumbers(a, Size);
    printf("Sum of Elements in this Array = %d \n", Addition);
    return 0;
}
Please Enter the Size of an Array : 7

Please Enter Array Elements  :  10 20 200 30 500 40 50
Sum of Elements in this Array = 850