Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Passing array to a function in 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("
The values are
");
    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)

Edit: 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
",sizeof(p1),sizeof(p2));
  else
    printf("Feeling lucky. %i == %i
",sizeof(p1),sizeof(p2));
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...