0
#include <stdio.h>

typedef struct {
    int num;
} test;


void print_test1d(test *t){
    for (int i = 0; i < 5; i++){
        printf("%d ",t[i].num);
    }
    printf("\n");
}

void print_test2d(test **t){
    printf("%s\n","Assert");
    for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            printf("%d\n",t[i][j].num);
        }
    }
}

void main() {
    
    test t[5];
    for (int i = 0; i < 5; i++){
        t[i].num = i;
    }
    
    print_test1d(t);


    test t2[5][5];
    for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            t2[i][j].num = i*j;
        }
    }

    print_test2d(t2);    
}

I am hoping someone can explain why when I attempt to create a 2d array of struct objects and pass them to the function print_test2d, I receive a segfault when the 1d example works. Thanks in advance.

These were the error warnings when I compiled

tester.c: In function ‘main’: tester.c:43:18: warning: passing
argument 1 of ‘print_test2d’ from incompatible pointer type
[-Wincompatible-pointer-types]
     print_test2d(t2);
                  ^~ tester.c:17:6: note: expected ‘test ** {aka struct <anonymous> **}’ but argument is of type ‘test (*)[5] {aka
struct <anonymous> (*)[5]}’  void print_test2d(test **t){

And this was the output:

0 1 2 3 4  Assert Segmentation fault (core dumped)
2
  • 1
    Does this answer your question? How to pass a 2D array by pointer in C? Commented Jun 21, 2020 at 4:54
  • It answers it perfectly!!! thanks for the quick response Commented Jun 21, 2020 at 8:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.