Results 1 to 2 of 2

Thread: pointer paradox

  1. #1

    Thread Starter
    Fanatic Member sbasak's Avatar
    Join Date
    Aug 2001
    Location
    Globe Trotter
    Posts
    524

    pointer paradox

    why this code gives error

    main()
    {
    int *x;
    *x = 5;
    printf("%d",*x);
    }


    it works with some compiler but not with others. If I use malloc, then it works fine everywhere. Can you tell why?
    Life is a one way journey, not a destination. Travel it with a smile and never regret anything.
    Yesterday is history, tomorrow is a mystery, today is gift - that's why we call it present.

  2. #2
    jim mcnamara
    Guest
    Yes.

    *x is supposed to point to some place in memory. At that place in memory is a variable of type int. Only you do not create any variable in memory for x to aim at.

    Just declaring like that has x referring to nothing. malloc() gives it something to refer to.
    Code:
    int main()
       int y;
       int *x;
       x = &y;
       *x = 5;
      printf("%d  %d\n",*x,y);
      return 0;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width