Looping an array of 2d arrays in C

Le sigh... Hopefully this will be the last time I have to ask for help on this topic. For a while now I've been working with a 1d array that holds 2d arrays. For reference you can view here. Now I'm just trying to loop through the elements with the following:

#include <stdio.h>

void arrbyptr(int (*ptr[2][2])[2]) {

int result;

    for ( int i = 0; i < 2; ++i ){
        for ( int j = 0; j < 2; ++j ){
            for ( int k = 0; k < 2; ++k ){
                result = (*ptr[j])[k];
                printf("%d\n", result);
            }
        }
    }
}

int main(void)
{
        int arr2d[2][2]={ {1,2},{3,4} };
        int arr2db[2][2]={ {5,6},{7,8} };

        int (*ptr[2][2])[2]= { { arr2d, arr2db } };

        arrbyptr(ptr);
}

It runs momentarily before segfaulting:

$ ./test
1
2
5
6
Segmentation fault

I get no errors or warnings from gcc. And yes, I understand logical errors will not show up. Tried to run this through strace, but can't find where its failing or why.

Any advice much appreciated.

Use gdb. We could probably point you to your problem but you need to learn how to use gdb.
the commands you need are:

compile & debug with

gcc filename.c -Wall -g -o filename
gdb filename
gdb>  break main
r 
[boom! it segfaults gdb will give you the exact line in the file]

Have fun.

1 Like

You have to follow the method I showed to-the-letter. (*arr[a][b])[c] is not the same as (*arr)[a][b][c].

void arrbyptr(int (*ptr[2][2])[2]) {
        int result, i, j, k;
    for ( i = 0; i < 2; ++i ){
        for ( j = 0; j < 2; ++j ){
            for ( k = 0; k < 2; ++k ){
                result = (*ptr)[j][k];
                printf("%d\n", result);
            }
        }
    }
}
2 Likes

Ah... That did the trick! Sorry, I guess I was confused as main called the function with (*ptr[2][2])[2] and the function's parameter was in the same format. Usually I try to brute-force every possible combination before posting anything, but I guess I missed that.

I haven't used gdb in a while, but I will have to start again. I'm just more used to strace from work.

Fortunately this should do me on calling all the arrays in this project. Next time I should be posting about a different topic. Much thanks again for all of your patience!