[英]how to move in bytes in an unsigned char in c
let's say that i have an unsigned char declared as follow : 假设我有一个未签名的char声明如下:
unsigned char Data[DATA_BLOCK_SIZE] = {0};
What is the meaning of expression Data+1
? Data+1
的含义是什么?
You don't have an unsigned char
, but an unsigned char []
. 您没有未
unsigned char
,但是没有unsigned char []
。 It means you have an array of unsigned char
. 这意味着您有一个
unsigned char
数组。 When you do arithmetic operations upon Data
, you move in this array. 对
Data
进行算术运算时,将在此数组中移动。
When you do Data + 1, it's like doing one of the following 当您执行Data + 1时,就像执行以下操作之一
&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
不是指针(您不能为其分配地址),但是当您使Data + 1
,隐式强制转换完成并且Data
等于其第一个块地址( &Data[0]
)。
Data
指向Data[0]
, Data + 1
指向Data[1]
。
Data+1
means the address of the second element in array Data
; Data+1
表示数组Data
第二个元素的地址; if you want to access the second element itself, you could use Data[1]
or *(Data+1)
, they are the same in C. 如果要访问第二个元素本身,则可以使用
Data[1]
或*(Data+1)
,它们在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. Data
保存数组中第一个元素的内存地址。 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) 将1加到该地址,您将获得数组中第二项的地址(即
Data[1]
,只有Data[1]
引用实际值 , Data+1
解析为内存地址)
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. 您经常会看到这种语法,主要是在循环中,因为它不需要使用
int i
或size_t len
类的临时变量。
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 现在,如果您编写:
Data[0]
,则与使用指针编写*(data+0)
相同:它取消引用它,从而获取存储在内存中的值
Writing Data+1
, then is the same as incrementing a pointer by 1: 写
Data+1
,与将指针增加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: 因此,在一个循环中,数数,说
'a'
的像‘惊奇’的字符串,一个可以这样写:
char word[] = "flabbergast";
int a_count = 0;
do
{
if (*word == 'a') ++a_count;
++word;
} while (*word != '\0');
Effectively using word
as an array. 有效地使用
word
作为数组。
Note that arrays and pointers are NOT the same thing 请注意,数组和指针不是一回事
Read this for details 详细阅读
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.