Ishmeet
Ishmeet

Reputation: 11

Structure pointer

#include<stdio.h>
int c;
int main()
{
        struct abc{
        int *a;
        char *ch[10];
        };
        struct abc obj1;
        struct abc *obj;
        obj = & obj1;
        scanf("%d",obj->a);
        printf("\nY");
        scanf("%s",&obj->ch);
        printf("\nY");
return 0;
}

I am using VIM editor and Gcc compiler on fedora.. i get an SEGMENTATION FAULT (CORE DUMPED??) //What does it mean??

Upvotes: 1

Views: 2219

Answers (4)

Mahesh
Mahesh

Reputation: 34665

i get an SEGMENTATION FAULT (CORE DUMPED??) //What does it mean??

A variable doing a memory access violation results segmentation fault.

scanf("%d",obj->a);

int *a; - struct member a is an uninitialized pointer but trying to take input on to the location it is pointing to. Causing you segmentation fault.

 obj->a = malloc(sizeof(int)) ;

Now you can take input for a pointing location.

 scanf("%d", &(obj->a) );

With the kind of input operations you perform, the struct definition need not need raw pointers -

struct abc{
    int *a;         // Change this to int a; or make a point to a valid memory location
    char *ch[10];   // Change this to char ch[10]; or initialize it with pointers pointing to a valid memory locations
                    // and then take input on to pointer pointing location.
};

Note the difference between the two -

int a  ;  // Can take input directly to "a"
int *a ;  // First "a" must point to a valid memory location that can hold an int
          // Then, can take input to "a" pointing location

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225252

"Segementation fault" means that your program tried to access memory that it wasn't allowed to. Your program has several pointer and initialization errors.

I think you want your array to be char ch[10], not char *ch[10]. You also need to change the scanf() call to match: scanf("%s", obj->ch);.

The same goes for your a field. It should probably not be a pointer, and you should pass a pointer to scanf():

scanf("%d", &obj->a);

Upvotes: 5

user418748
user418748

Reputation:

Your code invokes undefined behaviour.

You should have char ch[10]; and use scanf with a preset width to avoid overflows

scanf("9%s",&obj->ch); 

More : http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

The struct is defined to have a pointer-to-int, which you never initialize, hence pointing to random location, hence writing to a memory place you do not own, hence UB. Either switch that to a local variable int a or malloc() an integer.

Upvotes: 0

Anthony
Anthony

Reputation: 9581

Expanding on Carl's answer: char *ch[10] creates an array of 10 pointers to a character. What you want is an array to 10 characters.

Upvotes: 1

Related Questions