invalid type argument of ‘unary *’ (have ‘int’)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Siddarth777
    New Member
    • Sep 2010
    • 28

    invalid type argument of ‘unary *’ (have ‘int’)

    Code:
    #include<stdio.h>
    main()
    {
    int *a=5;
    int **p=&a;
    fflush(stdin);
    printf("%u,%u,%d",p,*p,**p);
    }
    getting compiled perfectly but am getting
    "segmentati on fault" in runtime
    please help
    Last edited by Banfa; Sep 18 '10, 10:21 AM. Reason: Added code tags
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The problem is that the pointer a does not point anywhere valid.

    You say it compiles perfectly, do you get no compiler warnings? If not you probably don't have you compiler warning level set high enough.

    The reason I say this is that on line 4 you assign an int to an int *. This effectively makes a point at memory location 5, almost certainly not a valid location on your system.

    p points to a

    So when you try to print

    p is valid, it is the address of a
    *p is valid it is a, the address of an int
    **p is not valid it is the thing that a points to, that is memory location 5, not the address of an allocate int and you get a segmentation fault (a memory address fault).

    You can not take the address of a numerical constant like 5.

    Comment

    • Siddarth777
      New Member
      • Sep 2010
      • 28

      #3
      thanks a lot for the reply
      i have a doubt
      in the above program in the statement
      int *a=5
      does that symbolizes implicitly that a value is holding the memory location of 5?
      i dint understand what is invalid about that......as am a newbie in c programming pointers concept
      please help

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        int *a=5;

        does explicitly set the value of a to (the memory location) 5. There is nothing wrong in that apart from being a little strange.

        The problem comes when you try to dereference a with *a, you try to access the memory location contained in a, in this case 5 and that is not a valid memory location, or a least one you do not have access rights to.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          Your code has a point to whatever int is stored at address 0x0005. The segmentation fault occurs because the operating system has not granted your program permission to access this address. In addition, you might get a run-time alignment fault if your program runs on one of the many processors that don't allow ints to be at odd addresses.

          Do you intend for a to point to an int whose value is 5? If so, then you want something like this:
          Code:
          int five = 5;
          int *a = &five;

          Comment

          Working...