here is some problem in structures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ashu

    #1

    here is some problem in structures

    lets take a look at the following code:-


    #include<stdio. h>
    #include<conio. h>
    struct tag{

    int age;
    char *name;
    }a;
    void main()
    {
    clrscr();
    puts("enter name ");
    scanf("%s",a.na me);
    fflush(stdin);
    puts("enter");
    scanf("%d",&a.a ge);
    printf("%s\t%d" ,a.name,a.age);
    getch();
    }

    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.
    why this is so,
    plz help me i m very confused

  • Chris Dollin

    #2
    Re: here is some problem in structures

    ashu wrote:
    [color=blue]
    > lets take a look at the following code:-
    >
    >
    > #include<stdio. h>
    > #include<conio. h>[/color]

    Nonstandard header. Avoid.
    [color=blue]
    > struct tag{
    >
    > int age;
    > char *name;
    > }a;[/color]

    `a.name` will be initialised with a null pointer.
    [color=blue]
    > void main()[/color]

    Nonstandard declaration for main. All bets are off. Avoid. `main`
    should return `int`.
    [color=blue]
    > {
    > clrscr();[/color]

    Nonstandard function. Also pointless. Avoid.
    [color=blue]
    > puts("enter name ");
    > scanf("%s",a.na me);[/color]

    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.
    [color=blue]
    > fflush(stdin);[/color]

    fflush takes an /output/ stream argument. Undefined behaviour. Avoid.
    If you want to eat characters until end of line, eat characters.
    [color=blue]
    > puts("enter");
    > scanf("%d",&a.a ge);[/color]

    scanf is NOT a wise choice for reading user input. Consider what might
    happen if the user responds "some cake", "deadbeef", "12345678987654 321".
    [color=blue]
    > printf("%s\t%d" ,a.name,a.age);[/color]

    No newline output, so result may not appear.
    [color=blue]
    > getch();[/color]

    Non-standard function. Avoid.
    [color=blue]
    > }
    >
    > 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.[/color]

    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.
    [color=blue]
    > why this is so,
    > plz help me i m very confused[/color]

    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

    Comment

    • Mike Wahler

      #3
      Re: here is some problem in structures

      "ashu" <riskyashish@ya hoo.com> wrote in message
      news:1139326202 .837834.121180@ o13g2000cwo.goo glegroups.com.. .[color=blue]
      > lets take a look at the following code:-
      >
      >
      > #include<stdio. h>
      > #include<conio. h>[/color]

      This is not a standard header. Please omit such
      from code posted here. It's not germane to your
      question anyway.
      [color=blue]
      > struct tag{
      >
      > int age;
      > char *name;
      > }a;[/color]

      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.
      [color=blue]
      > void main()[/color]

      int main(void)
      [color=blue]
      > {
      > clrscr();[/color]

      This is a nonstandard function. Please omit such from
      code posted here. It's not germane to your question
      anyway.
      [color=blue]
      > puts("enter name ");
      > scanf("%s",a.na me);[/color]

      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.
      [color=blue]
      > fflush(stdin);[/color]

      This is more undefined behavior. 'fflush()' behavior
      is only defined for output and update streams, not
      input streams.
      [color=blue]
      > puts("enter");
      > scanf("%d",&a.a ge);[/color]

      This is "OK" (other than that you didn't check for
      errors), since 'a.age' does provide storage for a
      type 'int' object.
      [color=blue]
      > printf("%s\t%d" ,a.name,a.age);[/color]

      More undefined behavior. You've passed an invalid pointer
      ('a.name') to 'printf()'.
      [color=blue]
      > getch();[/color]

      This is a nonstandard function. Please omit such from
      code posted here. It's not germane to your question
      anyway.
      [color=blue]
      > }
      >
      > its look ok to me,[/color]

      It is *not* OK. It is riddled with errors.
      [color=blue]
      > but as i run this, i face some problem,[/color]

      The problem is undefined behavior, which can range from
      'seems to work', to a crash, or anything in between.
      [color=blue]
      >i m not able
      > to assign value to name[/color]

      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.
      [color=blue]
      > 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.[/color]

      Yes, a type 'char*' value. That's not what you wrote, though.
      [color=blue]
      > why this is so,
      > plz help me i m very confused[/color]

      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_siz e);
      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


      Comment

      • Vladimir S. Oka

        #4
        Re: here is some problem in structures

        ashu wrote:[color=blue]
        > lets take a look at the following code:-[/color]

        Let's...

        First observation: don't use TABs, use spaces; while you're at it, feel
        free to add some horizontal whitespace -- it makes reading /much/
        easier.
        [color=blue]
        > #include<stdio. h>[/color]

        #include <stdio.h>
        [color=blue]
        > #include<conio. h>[/color]

        Non standard header. You don't even need it, as clrscr( ), and getch()
        I happen to know it provides, are not essential to your code.
        [color=blue]
        > struct tag{
        >
        > int age;
        > char *name;
        > }a;[/color]

        So far, so good...
        [color=blue]
        > void main()[/color]

        Standard C allows only:

        int main(void)

        or

        int main(int argc, char *argv[])
        [color=blue]
        > {
        > clrscr();[/color]

        Non-standard function, and not required.
        [color=blue]
        > puts("enter name ");
        > scanf("%s",a.na me);[/color]

        Now, here's where the problem lies (at least the one that you're
        complaining about -- others abound). Where have you allocated the space
        to hold your string. In the struct, `name` is just a pointer to a
        `char`. This is usually expected to be a number of `char`s holding a
        string, and terminated by a 0 character, but you need to allocate space
        for it first.
        [color=blue]
        > fflush(stdin);[/color]

        Behaviour of fflush() for `stdin` is undefined. It may work as you
        expected, but it may also flush your toilet for you every second
        Thursday.
        [color=blue]
        > puts("enter");
        > scanf("%d",&a.a ge);
        > printf("%s\t%d" ,a.name,a.age);[/color]

        You just love TABs, don't you. There's nothing wrong with them per se,
        but can you be sure how big they are on any given system your program
        may happen to run on?
        [color=blue]
        > getch();[/color]

        Another non-standard function.
        [color=blue]
        > }
        >
        > 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.[/color]

        Now, this is not true. You can assign a value to `a.name`, it's just
        not the value you'd like. Although your sentence is rather confusing, I
        suspect you tried:

        a.name = "a";

        and it worked fine. That would be because the compiler creates a
        (nameless) string literal "a", and then assigns its /address/ to
        `a.name`.

        Go back to your textbook and read more about pointers, and C strings.
        [color=blue]
        > why this is so,
        > plz help me i m very confused[/color]

        That, you most certainly are...

        PS
        I must have omitted to point at at least some errors, and probably
        wasn't precise enough in all instances, but others may feel like
        filling in the gaps...

        --
        BR, Vladimir

        Comment

        • pablo reda

          #5
          Re: here is some problem in structures

          Hey ashu, try this...

          struct tag{
          int age;
          char name[40]
          }a;

          Comment

          • Keith Thompson

            #6
            Re: here is some problem in structures

            Chris Dollin <kers@hpl.hp.co m> writes:[color=blue]
            > ashu wrote:
            >[color=green]
            >> lets take a look at the following code:-
            >>
            >>
            >> #include<stdio. h>
            >> #include<conio. h>[/color]
            >
            > Nonstandard header. Avoid.[/color]

            [snip]
            [color=blue][color=green]
            >> clrscr();[/color]
            >
            > Nonstandard function. Also pointless. Avoid.[/color]

            [snip]
            [color=blue][color=green]
            >> getch();[/color]
            >
            > Non-standard function. Avoid.[/color]

            I would place a slightly different emphasis on that. Non-standard
            headers and functions should be avoided *unless* there's a good reason
            to use them. They should also be avoided in code posted to this
            newsgroup.

            There's nothing wrong with using non-standard features *when it's
            necessary*.

            In this case, though, it's really not necessary. There's no standard
            and portable way to clear the screen (there may not be a screen), but
            there's no need for this program to clear the screen at all. Programs
            that clear my screen unnecessarily are seriously annoying; that's *my*
            information being erased. Likewise, if you need to wait for user
            input before terminating the program, a call to the standard getchar()
            should work as well as the non-standard getch(). I think getch() will
            return without waiting for a newline, but that's not a good enough
            reason to use it in this case.

            --
            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
            San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
            We must do something. This is something. Therefore, we must do this.

            Comment

            • Hemant Mohan

              #7
              Re: here is some problem in structures

              you have not allocated any memeoy to name

              Comment

              • Hemant Mohan

                #8
                Re: here is some problem in structures

                You have not allocated any memory to name. This code should give you a
                crash.
                Ofcourse you need to avoid usage of non-standard headers and functions.

                Comment

                • Nelu

                  #9
                  Re: here is some problem in structures

                  Hemant Mohan wrote:[color=blue]
                  > You have not allocated any memory to name. This code should give you a
                  > crash.
                  > Ofcourse you need to avoid usage of non-standard headers and functions.
                  >[/color]
                  Please read http://cfaj.freeshell.org/google/
                  before posting again.

                  Thank you very much!

                  --
                  Ioan - Ciprian Tandau
                  tandau _at_ freeshell _dot_ org (hope it's not too late)
                  (... and that it still works...)

                  Comment

                  Working...