Pointer arithmetic and arrays: what is really legal?

Consider the following statements:

int    *pFarr, *pVarr;

int    farr[3] = {11,22,33};
int    varr[3] = {7,8,9};

pFarr = &(farr[0]);
pVarr = varr;

At this point, both pointers point to the beginning of each address of the corresponding array. For * pFarr, we are now looking at 11 and for * pVarr, 7.

Equally, if I request the contents of each array through * farr and * varr, I also get 11 and 7.

So far so good.

Now try pFarr++and pVarr++. Fine. Now we look at 22 and 8, as expected.

But now...

An attempt to move up farr++and varr++... and we get "the wrong type of argument to increase".

Now I find out the difference between an array pointer and a regular pointer, but since their behavior is similar, why is this a limitation?

, , , , , , !?

working_on_pointers ( pFarr, farr );  // calling with expected parameters
working_on_pointers ( farr, pFarr );  // calling with inverted parameters 

.

void working_on_pointers ( int *pExpect, int aExpect[] ) {

    printf("%i", *pExpect);  // displays the contents of pExpect ok
    printf("%i", *aExpect);  // displays the contents of aExpect ok

    pExpect++;               // no warnings or errors
    aExpect++;               // no warnings or errors

    printf("%i", *pExpect);  // displays the next element or an overflow element (with no errors)
    printf("%i", *aExpect);  // displays the next element or an overflow element (with no errors)

}

- , , ?

.

: Noobs, , : http://www.panix.com/~elflord/cpp/gotchas/index.shtml b >

+5
6

, farr++, - , - , farr . . 3.

, , , . . C. ,

void f(int *a);
void f(int a[]);

, - , "" .

- :

void f(void (*p)());
void f(void p()); 

, ( ), , - ​​ :

f = NULL; // error!

, .

+7

C . , :

T data[N];

T - , N - , :

data = ...;

data++; data, .

C . , , .

- sizeof (&data) . . .

, :

void working_on_pointers ( int *pExpect, int aExpect[] ) {

void working_on_pointers ( int *pExpect, int *aExpect ) {

, , , , .

:

. C , .

+5

farr varr , . . , ( sizeof -), (rvalue) , . 17. int, 17, 17 . .

, : , "" . , working_on_pointers, aExpect pExpect . , aExpect " int". , , .

+1

, . .

int * ptr = (int *)malloc(2* sizeof(int));
ptr[0]=1;
ptr[1]=2;

printf ("%d\n", ptr[0]);
printf ("%d\n", ptr[1]);

, .

:

, "" [], . a [i], "a" , , , p [i] ( , 2.2). x [i] ( x - ) * ((x) + (i)).

: http://www.lysator.liu.se/c/c-faq/c-2.html

-1

.

i.e

int farr[]

const int * farr

; "" . , farr ++, , , .

, , , .

P.S: , C, . - .

-2

All Articles