0

I know it's very basic but I MUST understand the concept, why it doesn't work?

void printMat(int arr[N][N], int n)
{
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            if (i < j)
            {
                arr[i][j] = 0;
            }

            {
                arr[i][j] = i+j+2;
            }

}

int** triDown(int arr[N][N], int n)
{
    int i, j, **a;
    for(i = 0; i < n; i++)
    {
        *(a+i) = (int*)malloc(sizeof(int)*(i+1));
    }

    for(i=0;i<n;i++)
        for(j=0;j<i+1;j++)
        {
            a[i][j] = arr[i][j];
        }
    return a;
}

void main()

{
    int *arr[N],**NewMat;

    printMat(arr,N);
    NewMat = triDown(arr,N);
}

I'm having a really hard time trying to understand the pointer-to-pointer thing when it comes to functions and dynamic allocations. What should've been done in NewMat func?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Itay Zaguri
  • 43
  • 1
  • 7
  • 1
    any error message you are receiving? – Eray Balkanli Nov 07 '15 at 17:38
  • 3
    This isn't about a double pointer to a function, but a double pointer (or really pointer to pointer) to `int`. Also, types `int arr[N][N]` and `int *arr[N]` are *not* the same thing in C. You need to make them consistent, or at least you can pass `int arr[N][N]` to `int *arr[N]` but not the other way around. – lurker Nov 07 '15 at 17:39
  • why its not the same thing? thats what i dont understand – Itay Zaguri Nov 07 '15 at 17:58

1 Answers1

2

int a[N][N] and int *a[N] are never compatible. The first is a two-dimensional array of int values, while the second is a one-dimensional array of int pointers. You need to declare it as int (*a)[N] for a compatible pointer type. Then you can pass it an int a[N][N] as an argument, just as you would in the one-dimensional case where you pass an int a[N] to an int *a.

But you need to declare the actual array in main, not just a pointer to it. Note that int (*a)[N] is only a single pointer value, so its size will most likely be 4 or 8 depending on your architecture.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41