pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gretchen1
    New Member
    • Nov 2007
    • 5

    pointers

    I am having a hard time with this:

    Which statement is true given the following declaration:

    int n=5, *p=&n;

    a) p is a pointer initialized to point to n.
    b) p is a pointer initialized to the value 5.
    c) n and p are both pointer variables.
    d) The declaration contains a syntax error.
  • beacon
    Contributor
    • Aug 2007
    • 579

    #2
    Think of a pointer as a variable that has to have an asterisk before it. That's the only difference between the two.

    If n is an integer, it will hold an integer value.

    If *p is declared as an integer, it will hold the address for an integer value, which means that when *p is dereferenced, you will get an integer returned.

    However, even though n and *p are both integers, they have to be declared separately just like a float and a double would, or how a string and a character would.

    Does this clear it up a little?

    Comment

    • drhowarddrfine
      Recognized Expert Expert
      • Sep 2006
      • 7434

      #3
      Assuming *p is declared as a pointer to an integer:
      int *p;
      you are saying p points at an integer.

      Saying *p=&n is saying make the integer p is pointing at equal to & (the address of) the integer n. But p is supposed to point to an integer so this is incorrect.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by drhowarddrfine
        Saying *p=&n is saying make the integer p is pointing at equal to & (the address of) the integer n. But p is supposed to point to an integer so this is incorrect.
        Not in initialisation

        [code=c]
        int n=5;
        int *p;

        *p = &n;
        [/code]In this example p is declared and then not initialised. This code says make the int p points at equal to the address of the integer n (probably but not always wrong).

        [code=c]
        int n=5;
        int *p = &n;
        [/code]In this code p is declared and initialised at the same time. This says p is a pointer to an integer and it's value is the address of the integer n.

        These 2 code sames result in different assignments, the first assigns to *p and the second assigns to p.

        Comment

        Working...