Ruizhi Ruizhi - 1 year ago 138
C Question

Pointer: p++ & p+1

I am currently study pointer, but i have got few questions:

  1. When we say
    int a[] = {10, 11}; int *p = a
    , the compiler would allocate memory for the pointer
    (which points to the first address of the array). But if we say
    p + 1
    , does that mean that some memory has been initialized with a new pointer called
    p + 1

  2. If the answer to the above is negative, i.e. no memory has been allocated for
    p + 1
    : When we use
    *(p + 1)
    , we still can get the value
    . Does that mean that this symbol
    can be used without a pointer (as long as we know the address)?

Answer Source

Yes, * can be used without a pointer variable, it's just an operator. It needs to be applied to an expression of a pointer type, but that expression doesn't have to be a single variable name.

For example:

int x = 42;

*(&x) = 4711;

The above sets x to 4711 using the * operator, but there's no separate pointer variable in the code. The type of the value returned by &x is of course int *, i.e. "pointer to integer", and that's a type that * can be used with.

The expression p + 1 is just an expression, it can be evaluated and the result can be used (or thrown away, depending on the context). It's not "a pointer", although the resulting value is a pointer the expression itself is not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download