let's say that i have an unsigned char declared as follow :
unsigned char Data[DATA_BLOCK_SIZE] = {0};
What is the meaning of expression Data+1
?
let's say that i have an unsigned char declared as follow :
unsigned char Data[DATA_BLOCK_SIZE] = {0};
What is the meaning of expression Data+1
?
You don't have an unsigned char
, but an unsigned char []
. It means you have an array of unsigned char
. When you do arithmetic operations upon Data
, you move in this array.
When you do Data + 1, it's like doing one of the following
&Data[1]
(&Data[0]) + 1
It is called pointer arithmetic. Data
is not a pointer (you can not assign an address to it) but when you make Data + 1
, an implicit cast is done and Data
equals its first block address (&Data[0]
).
Data
points to Data[0]
, Data + 1
will point to Data[1]
.
Data+1
means the address of the second element in array Data
; if you want to access the second element itself, you could use Data[1]
or *(Data+1)
, they are the same in C.
Arrays and pointers are not the same thing, but they behave in a similar fashion, like here. Data
holds the memory address of the fist element in the array. Like a pointer holds the memory address of something.
Add 1 to that address, and you get the address of the second item in the array (ie Data[1]
, only Data[1]
refers to the actual value, Data+1
resolves to the memory address)
You see this syntax pretty often, mainly in loops because it doesn't require one to use a temp variable like int i
or size_t len
or something.
In your case, an illustration to erase all doubt:
Data = 0x01 //value of Data
//layout in memory
0x01 0x02 0x03 0x04 0x05
| \0 | \0 | \0 | \0 | \0 |
Now if you write: Data[0]
, it's the same as writing *(data+0)
with a pointer: it dereferences it, thus fetching the value stored in memory
Writing Data+1
, then is the same as incrementing a pointer by 1:
Data+1 == 0x02 != Data[1]
//because:
Data[1] == *(Data+1);
So in a loop, counting the number of, say 'a'
's in a string like "flabbergast", one could write:
char word[] = "flabbergast";
int a_count = 0;
do
{
if (*word == 'a') ++a_count;
++word;
} while (*word != '\0');
Effectively using word
as an array.
Note that arrays and pointers are NOT the same thing
Read this for details