传球达阵在C函数 [英] Passing array to a function in C

查看:119
本文介绍了传球达阵在C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我们声明函数带有一个整型数组,我们通过数组功能的地址。在简单的整数的情况下,如果我们通过地址我们得到指针转换错误提示错误。但如何其可能在数组的情况下

Though we declare a function with an integer array, we pass address of the array to the function. In the case of simple integers it gives error if we pass address we get pointer conversion error. But how its possible in case of an array

#include<stdio.h>
void print_array(int array[][100],int x, int y);
main()
{
    int i,j,arr[100][100];
    printf("Enter the array");
    for(i=0;i<2;i++)
    {
        for(j=0;j<2;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    print_array(arr,i,j);

}

void print_array(int array[][100],int x,int y)
{
    int i,j;
    printf("\nThe values are\n");
    for(i=0;i<x;i++)
    {
        for(j=0;j<y;j++)
        {
            printf("%d",array[i][j]);
        }
    }
}

我的问题是,即使我们的函数声明为一个整数数组作为第一个参数(在这里)我们传递阵列地址,当我们调用该函数。它是如何发挥作用?

My question is even though our function is declared as one with integer array as first parameter (here) we are passing array address when we call the function. How does it function?

推荐答案

您是路过的数组,而不是它的地址。
改编是一个int [] []数组
(实际上它是pretty一样及(ARR [0]),这是一个指针(地址)阵列的第一行在C,有一个数组,对应的指针之间没有实际的区别,只是你把它与&安培的地址;运营商)

Your are passing the array, not its address. arr is an int[][] array (in fact it is pretty the same as &(arr[0]), which is a pointer to (the address of) the first line of your array. In C, there is no practical difference between an array and the corresponding pointer, except you take it's address with the & operator.)

编辑:好吧,只是为了让我清楚的:

Ok, just to make me clear:

#include <stdio.h>

int fn(char p1 [][100], char (*p2)[100])
{
  if (sizeof(p1)!=sizeof(p2))
    printf("I'm failed. %i <> %i\n",sizeof(p1),sizeof(p2));
  else
    printf("Feeling lucky. %i == %i\n",sizeof(p1),sizeof(p2));
}

int main()
{
  char arr[5][100];
  char (*p)[100]=&(arr[0]);
  fn(arr, arr);
  fn(p, p);
  return 0;
}

这篇关于传球达阵在C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆