Re: here is some problem in structures



ashu wrote:

lets take a look at the following code:-


#include<stdio.h>
#include<conio.h>

Nonstandard header. Avoid.

struct tag{

int age;
char *name;
}a;

`a.name` will be initialised with a null pointer.

void main()

Nonstandard declaration for main. All bets are off. Avoid. `main`
should return `int`.

{
clrscr();

Nonstandard function. Also pointless. Avoid.

puts("enter name ");
scanf("%s",a.name);

Attempt to store characters through a null pointer. All bets are off.
If you're lucky, you'll get some kind of crash at this point. Also
scanf is NOT a wise choice for reading user input.

fflush(stdin);

fflush takes an /output/ stream argument. Undefined behaviour. Avoid.
If you want to eat characters until end of line, eat characters.

puts("enter");
scanf("%d",&a.age);

scanf is NOT a wise choice for reading user input. Consider what might
happen if the user responds "some cake", "deadbeef", "12345678987654321".

printf("%s\t%d",a.name,a.age);

No newline output, so result may not appear.

getch();

Non-standard function. Avoid.

}

its look ok to me, but as i run this, i face some problem, i m not able
to assign value to name
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.

If `a` is declared within `main`, then `a.name` will have some random
undefined value and, if you're unlucky, may point somewhere so the
machine doesn't catch it and crash.

why this is so,
plz help me i m very confused

It's a fine concoction of undefined behaviours you have there. I'd
advice picking up a decent C book and starting through it or, if the
above commentary gives you the willies, try a less spikey language.

--
Chris "try, or try not -- there is no do" Dollin
.



Relevant Pages