ashu said:
lets take a look at the following code:-
#include<stdio.h>
#include<conio.h>
This is not a standard header. Please omit such
from code posted here. It's not germane to your
question anyway.
struct tag{
int age;
char *name;
}a;
Note that 'a.name' is a pointer. It can store
an address. But you've not assigned it the value
of any address. If you do, it must be the address
of memory which is part of your program.
int main(void)
This is a nonstandard function. Please omit such from
code posted here. It's not germane to your question
anyway.
puts("enter name ");
scanf("%s",a.name);
This gives undefined behavior. 'scanf()' will try
to store data at the address stored in 'a.name'.
But 'a.name' does not contain the address of memory
which is part of your program.
This is more undefined behavior. 'fflush()' behavior
is only defined for output and update streams, not
input streams.
puts("enter");
scanf("%d",&a.age);
This is "OK" (other than that you didn't check for
errors), since 'a.age' does provide storage for a
type 'int' object.
printf("%s\t%d",a.name,a.age);
More undefined behavior. You've passed an invalid pointer
('a.name') to 'printf()'.
This is a nonstandard function. Please omit such from
code posted here. It's not germane to your question
anyway.
It is *not* OK. It is riddled with errors.
but as i run this, i face some problem,
The problem is undefined behavior, which can range from
'seems to work', to a crash, or anything in between.
i m not able
to assign value to name
A value can be assigned to 'name'. But 'name' is a *pointer*.
The only valid values which can be assigned are addresses of
type 'char' objects. But that's not what your code does.
but as i declare a structure's instance i.e, "a" within the main
program, i m able to assign a value in a.name.
Yes, a type 'char*' value. That's not what you wrote, though.
why this is so,
plz help me i m very confused
You need to provide storage for your 'name' pointer to point to.
You have a couple options:
Change your pointer to an array:
#define SOME_SIZE 100 /* you decide what this value should be */
struct tag
{
int age;
char name[SOME_SIZE];
} a;
(this will fix at compile time the maximum number of
characters that 'name' can store).
or:
#include <stdlib.h>
struct tag
{
int age;
char *name;
} a;
size_t some_size = 100; /* Again, this is my arbitrary value. */
/* You may want to calculate this value */
int main(void)
{
a.name = malloc(some_size);
if(a.name)
{
/* store characters at address 'a.name' */
}
free(a.name);
return 0;
}
(this will allow you to determine at run-time how
many characters to allocate for your data).
In both cases above, if you're wanting to store a
string, be sure to allow an extra byte for the
string terminator.
Finally:
Repeat to yourself until it sinks in:
"A pointer is not an array. An array is not a pointer."
Which C book(s) are you reading?
-Mike