Learner_51
Learner_51

Reputation: 1075

Segmentation fault when printing an array

When I try to pass my array to a function and print it's values, I get a Segmentation fault error. I am very new to C programming and was trying to figure this out for a long time. Any help will be greatly appreciated. Please show me the solution with sample code if possible.

#include<stdio.h>
#include<stdlib.h>

void myfun(int **arr);

int main(int args, char** argv)
{            
    int arr[3][3] = {{3, 8, 6}, {2, 3, 2}, {4, 1, 2}};  
    myfun((int **) arr[3]);  
    return 0;
}

void myfun(int **arr) 
{
   int i;   
   for(i=0; i<3; i++) 
   {      
      printf("arr[1][i]:%d\n",arr[1][i]);//Gives Segmentation fault
   }   
}

Upvotes: 0

Views: 55

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84531

In addition to your function parameter issues, you also have your array indexes swapped in the function. i.e.:

#include<stdio.h>
#include<stdlib.h>

void myfun (int arr[][3]);

int main (void)
{            
    int arr[3][3] = {{3, 8, 6}, {2, 3, 2}, {4, 1, 2}};  
    myfun (arr); 

    return 0;
}

void myfun (int arr[][3]) 
{
    int i;   

    for(i=0; i<3; i++) 
    {      
        printf (" arr[i][1]:%d\n", arr[i][1]); // OK now
    }   
} //result  show 8, 3, 1

Output

$ ./bin/arr_pass_2d
 arr[i][1]:8
 arr[i][1]:3
 arr[i][1]:1

Note: arr[i][1] not arr[1][i]

Additionally, if you update your printf call in the function, you can include the row value as well. e.g.:

    printf (" arr[%d][1]:%d\n", i, arr[i][1]);

Output

$ ./bin/arr_pass_2d
 arr[0][1]:8
 arr[1][1]:3
 arr[2][1]:1

Upvotes: 1

dbush
dbush

Reputation: 223699

You can't pass a two dimensional array as a double pointer. For a multidimentional array, the function needs to know all dimensions except the last one.

So define myfunc like this:

void myfun(int arr[3][3]);

And call it like this:

myfun(arr);

Upvotes: 1

Related Questions