InsaneCoder
InsaneCoder

Reputation: 8268

Segmentation fault error in gcc

Why the following code is giving segmentation fault error

#include<stdio.h>
int main()
{
    int i;
    int a[2][2]={1,2,3,4};

    int **c;
    c=a;
    for(i=0;i<4;i++)
        printf("%d",*(*(c)+i));
}

Upvotes: 0

Views: 279

Answers (3)

yulian
yulian

Reputation: 1627

Read the comments of the following code:

#include<stdio.h>

int main()
{
    int i;
    int a[2][2]={{1,2},{3,4}};    // Put each dimension in its braces

  /*int a[2][2]={1,2,3,4}; 
    This declaration of array make the following: 

       a1[ONE]           a2[TWO]           THREE           FOUR 
       a3[Unknown value] a4[Unknown value] 

    i.e. the numbers 3 and 4 are being written beyond of the array...
  */

    int *c1;
    int **c2;                     // `int **` is a pointer to a pointer, so you have to
    c1=&a[0][0];                  // declare a pointer `c1` and then assign to it `c2`.
    c2=&c1;                       // AND use `&` to assing to pointer the address of 
                                  // variable, not its value.
    for(i=0;i<4;i++)
        printf("%d",*(*(c2)+i));  // here is `double dereference` so here must be `c2`
                                  // (ptr-to-ptr-to-int) but not c1 (ptr-to-int).
    return 0;                     // AND make the `main()` to return an `int` or
                                  // make the returning type `void`: `void main(){}`
                                  // to make the `main()` function to return nothing.
}

Upvotes: 2

Freddie
Freddie

Reputation: 891

This is a problem in the definition of c. int **c; Suggests that this is a pointer to a pointer, but the definition of a is of type int *[2]. Changing the definition of c to int (*c)[2] should do the trick.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224834

This assignment:

c=a;

Should give you a warning. a decays into a pointer to its first element, which has type int (*)[2]. Assigning that type to a variable of type int ** requires an explicit cast.

Redeclaring c should fix your problem:

int (*c)[2];

Example warning from clang:

example.c:8:6: warning: incompatible pointer types assigning to 'int **' from
      'int [2][2]' [-Wincompatible-pointer-types]
    c=a;
     ^~
1 warning generated.

Upvotes: 7

Related Questions