简体   繁体   中英

C Pointer for 2-dimensional Array

Already declared is an array such as:

char ma[10][20];

The address of a specific element is gotten using:

p = &ma[1][18];

Which element will p point to after p++; ?

Adding 1 to a address of member of array, get the address of the next member. since p is the address of ma[1][18] , which is member of the array ma[1] , p+1 is the address of ma[1][19] . (And of course, p++; is like p=p+1; )

Edit: I assumed, of course, that p is char* . If it's something else, the answer can be other.

p++ yields &ma[1][19]

Here is the explanation:

char ma[10][20];
char *p = &ma[1][18];

p value is &ma[1][18] which is equal to *(ma + 1) + 18 .

So p++ value which is equal to p + 1 is equal to (*(ma + 1) + 18) + 1 equal to *(ma + 1) + 19 which is equal to &ma[1][19] .

You don't specify the type of p ; assuming it's char * , then p++ will advance it to ma[1][19] (1 char).

Here are a couple of variations:

char (*p)[20] = &ma[1];

In this case, p is a pointer to a 20-element array of char , initialized to point to ma[1] ; executing p++ will advance p to point to ma[2] (20 chars).

char (*p)[10][20] = &ma;

In this case, p is a pointer to a 10-element array of 20-element arrays of char , initialized to point to ma ; executing p++ will advance p to the next element immediately following ma (200 chars).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM