#include <stdio.h>

struct sss {

int a;

};

int main(void)

{

struct sss *ptr;

puts("Enter value for (*ptr).a :");

scanf("%d",&(*ptr).a);

printf("(*ptr).a holds value %d\n",(*ptr).a);

}

OUTPUT

Enter value for (*ptr).a :

4

(*ptr).a holds value 4

Interested to execute the above code and check the output, normally fresh guy will do that, there is a big bug there. And one more thing (*ptr).a = ptr -> a , you can substitute this and check once again.

At

struct sss *ptr; line I just declared a pointer of type(data type) struct sss, but then I had not assigned(pointed) it to any thing. So on executing above code will through the below error.

$ ./a.out 

enter value for ptr->a
2
Segmentation fault

“Segmentation fault” this error tells that it is a NULL pointer exception, a man master of manythings finds it easier. But a fresh guy it becomes a nightmare.

Solution to this

Make the pointer to point something

It can be done in two ways

1) Make the pointer to point the same type variable,

#include <stdio.h>

struct sss

{

int a;

};

int main(void)

{

struct sss *ptr, var;

ptr = &var;

puts("Enter value for ptr -> a :");

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

printf("ptr -> a holds value %d\n",ptr -> a);

}

Why can’t we test it with other types,

#include <stdio.h>

struct sss

{

int a;

};

int main(void)

{

struct sss *ptr;

char var; // you can check with int var; too

ptr = &var;

puts("Enter value for ptr -> a :");

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

printf("ptr -> a holds value %d\n",ptr -> a);

}

You will get the same output, but at compile time you can see this warning message.

warning: assignment from incompatible pointer type

2) Dynamically allocating memory and making pointer to point such memory.

#include <stdio.h>

struct sss

{

int a;

};

int main(void)

{

struct sss *ptr;

ptr = (struct sss *)malloc(sizeof(struct sss));

puts("Enter value for ptr -> a :");

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

printf("ptr -> a holds value %d\n",ptr -> a);

}

At

ptr = (struct sss *)malloc(sizeof(struct sss));

I am allocating memory dynamically and making my pointer to point the starting address of that memory.

Hence my code will run without bug.

Enjoy..!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s