char * 和 int * 的区别
在学习过程中遇到了对单片机LCD外设内存地址操作的问题,问题如下
例如内存的起始地址是0XA20(内存分布如下),
定义一个变量add = 0XA20(代表LCDM1);访问下一个地址(如LCDM2)时采用add+1的操作
我应该怎么利用变量来操作地址里面的内容呢?
方法一:
*(unsigned char *)add = 0X0F; // LCM1
*(unsigned char *)(add+1) = 0X0F; // LCDM2
方法二:
*(unsigned char *)add = 0X0F; // LCM1
*((unsigned char *)add+1) = 0X0F; // LCDM2```c
方法三:
*(unsigned int *)add = 0X0F; // LCM1
*(unsigned int *)(add+1) = 0X0F; // LCDM2
方法四:
*(unsigned int *)add = 0X0F; // LCM1
*((unsigned int *)add+1) = 0X0F; // LCDM2
#include "stdio.h" int main() { char c_buf[5] = {1,2,3,4,5}; int z_buf[5] = {6,
7,8,9,10}; char *c = c_buf; int *z = z_buf; int a = 1245; printf("sizeof(c) =
%ld\n",sizeof(c)); printf("sizeof(z) = %ld\n",sizeof(z)); printf("c_add = %p\n",
c); printf("z_add = %p\n",z); printf("c_add+1 = %p\n",c+1); printf("z_add+1 =
%p\n",z+1); printf("(char *)a = %p\n",(char *)a); printf("(char *)(a+1) = %p\n",
(char *)(a+1)); printf("(int *)a = %p\n",(int *)a); printf("(int *)(a+1) = %p\n"
,(int *)(a+1)); printf("(char *)a = %p\n",(char *)a); printf("(char *)a+1 =
%p\n",(char *)a+1); printf("(int *)a = %p\n",(int *)a); printf("(int *)a+1 =
%p\n",(int *)a+1); return 0; } 运行结果如下: sizeof(c) = 8 sizeof(z) = 8 c_add =
0x7ffea5a70960 z_add = 0x7ffea5a70940 c_add+1 = 0x7ffea5a70961 z_add+1 =
0x7ffea5a70944 (char *)a = 0x4dd (char *)(a+1) = 0x4de (int *)a = 0x4dd (int *)(
a+1) = 0x4de (char *)a = 0x4dd (char *)a+1 = 0x4de (int *)a = 0x4dd (int *)a+1 =
0x4e1
分析下代码和答案,就知道该怎么选则合适了,方法一、二、三,看着都是可以的,但是因为内存偏移是一个字节,所以最好还是别使用方法三(毕竟出问题就凉凉了)。
遇到数值强转为指针时,强转为指针是(char *)还是(int * )呢?我们根据内存的偏移大小来确定的。
自己遇到问题及解决记录的,如有问题欢迎指出,谢谢