-1

I just want to print out a static array (2D array) in C using functions. I use gcc as my compiler. When I try to run my code it gives me a seg fault and I dont have any idea why:

#include <stdio.h>

void print_out_an_array(int n, int m, int tab[n][m])
{
    int i,j;
    for(i=0; i<n; i++)
        for(j=0; j<m; j++)
            printf("tab[%d][%d] = %d\n", i, j, tab[i][j]);
}

int main(int argc, char **argv)
{
    int tab[2][4] = {{1,2,3,4}, {5,6,7,8}};
    print_out_an_array(tab, 2, 4);

    return 0;
}
Brian Brown
  • 3,873
  • 16
  • 48
  • 79

3 Answers3

3

your function call and function definition doesnt match

your function call
print_out_an_array(tab, 2, 4); but in function definition your first argument is int
void print_out_an_array(int n, int m, int tab[n][m])

make the arguments same, like:

change function call to
``print_out_an_array(2, 4, tab);`

update:
check this code it works

and also read this for reference C, passing 2 dimensional array

Community
  • 1
  • 1
exexzian
  • 7,782
  • 6
  • 41
  • 52
3

In your function definition, first parameter is int type but you are calling your function with first argument as int **. Change your function call to

print_out_an_array(2, 4, tab);  

About the question in your comment:

Ok, but how about this code: http://ideone.com/Z4mHkb why it gives me an error?

Function parameters **tab and tab[n][m] are not equivalent. Compiler, on seeing tab [m][n] as function parameter, interprets it as

void fun(int (*)[m]tab, int n, int m)

i.e , it interprets tab as a pointer to an array of m integers. While on seeing int **tab, it simply interprets tab as a pointer to a pointer to integer (or an array of pointers ( int *tab[]) to int ).

haccks
  • 104,019
  • 25
  • 176
  • 264
2

Instead of answering the original solution whose solution is obvious, I answer the other one from your comment.

Your array is a

int[][N]

while you pass a

int ** to your function.

These are completely different from each other:

  • An int[][N] has all values from all dimensions beneath each other.
  • An int **, however, points to one or more pointers, in turn pointing to the real values.

At int[][], you can omit one level of indirection and can turn it into a

int (*)[N]

i. e. a pointer to an array. This array must be of determined size, which isn't fulfilled in your case as well.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • I think what you wrote here is the most important part. Where can I read about it more? – Brian Brown Nov 14 '13 at 19:50
  • @BrianBrown In a good C book or tutorial (but, alas, I can't name one). And surely in many Q/As here on SO (but I cannot tell a concrete one, but there must be many). – glglgl Nov 14 '13 at 22:32