0

I am trying to pass the input array to the main() function, but the array is still empty after executing the enter_array() function.

I get the message "Process finished with exit code -1073741819 (0xC0000005)"

Could someone please explain to me, what should I correct in order to be able to read this newly created array in main()? Here's my code:

#include <stdio.h>

int** enter_array(){
    int a[2][2];
    int row_id = 0;
    int element_id = 0;
    while (row_id<2){
        while (element_id<2){
            printf("Element number %d in row number %d:",element_id,row_id);
            scanf("%d", &a[row_id][element_id]);
            element_id++;
        }
        row_id++;
        element_id = 0;}
    return a;
}
int main() {
    int **a;
    a = enter_array();
    int row_id = 0;
    int element_id = 0;
    while (row_id<2){
        while (element_id<2){
            printf("%d", a[row_id][element_id]);
            element_id++;}
        row_id++;
        element_id = 0;
        printf("\n");}
    return 0;
}
  • 1
    A 2D array is not a double pointer, and is not compatible with a double pointer. – John Bollinger Sep 10 '22 at 14:07
  • Moreover, you are trying to return (a pointer into) a *local variable*. The lifetime of that variable ends when the function returns. If you want an object to be allocated during the execution of a function whose lifetime extends past the end of the function's execution, then you must allocate it dynamically. – John Bollinger Sep 10 '22 at 14:09
  • No matter if you are dealing with 1D or 2D arrays, returning the address of a local variable will never work. The address will be invalid as soon as you leave the function – Gerhardh Sep 10 '22 at 14:10
  • The easiest route might be to declare your array in `main()`, pass (a pointer into) that array to `enter_array()`, and have the latter function populate it. – John Bollinger Sep 10 '22 at 14:12
  • Thank you very much, now everything's fine – kazimierz___tetmajer Sep 10 '22 at 15:25

0 Answers0