这里有一个简单的加法例子,减法也是这样。
请注意,当您让编译器完成这项工作并使用数据类型和指针时,算法会为您提供帮助+1或-1到您的
指针
是移动到下一个项目,您不必担心数据是否在一个字节、2个字节或8个以上字节中。
看起来您自己在做所有的工作,将地址保存在变量中
unsigned long
您认为这是理所当然的64位寻址{或者如果您只是
unsigned int
这是32位寻址,如果有超过2^32字节的可寻址空间},希望您能认识到问题所在。因此,我的建议是使用指针,尤其是在处理超过1字节的数据时。
unsigned long *pAddress;
意味着pAddress保存一个作为地址的值,因为它被定义为一个指针
*
它指向内存中类型为无符号长整数的数据。内存中的字节数是
无符号长
这取决于你的系统,是在系统层面上处理的事情,也是你通常不必或应该担心的事情。但在今天的计算机上,它可能是64位或长整数。
我认为,一旦您了解了这一点,就会变得很容易:
#include <stdio.h>
int main ( int argc, char *argv[] )
{
char a[8];
short int b[8];
int c[8];
long int d[8];
float e[8];
double f[8];
char *pa;
short int *pb;
int *pc;
long int *pd;
float *pe;
double *pf;
pa = a;
pb = b;
pc = c;
pd = d;
pe = e;
pf = f;
printf(" address of a is %p\n", pa );
printf(" address of b is %p\n", pb );
printf(" address of c is %p\n", pc );
printf(" address of d is %p\n", pd );
printf(" address of e is %p\n", pe );
printf(" address of f is %p\n", pf );
printf("\n");
printf(" address of a+1 is %p\n", pa+1 );
printf(" address of b+1 is %p\n", pb+1 );
printf(" address of c+1 is %p\n", pc+1 );
printf(" address of d+1 is %p\n", pd+1 );
printf(" address of e+1 is %p\n", pe+1 );
printf(" address of f+1 is %p\n", pf+1 );
printf("\n");
printf(" sizeof( char ) is %ld\n", sizeof( char ) );
printf(" sizeof( short int ) is %ld\n", sizeof( short int ) );
printf(" sizeof( int) is %ld\n", sizeof( int ) );
printf(" sizeof( long int ) is %ld\n", sizeof( long int ) );
printf(" sizeof( float ) is %ld\n", sizeof( float ) );
printf(" sizeof( double ) is %ld\n", sizeof( double ) );
printf("\n");
}