1. 程式人生 > >c++指標加數字

c++指標加數字

#include<stdio.h>
#include<string.h>
intmain()
{
charbuffer[1024]={0,1,2,3,4,5,6,7};
intiTest=0x12345678;//16進位制1位表示4bititest表示4byte
int*p=(int*)(buffer+7);//指標+數字表示表示擷取陣列,buffer7位開始以後的陣列
printf("intlen:%ditestlen:%ditest:%d\n",sizeof(int),sizeof(iTest),iTest);
memcpy(p,&iTest,sizeof(iTest));
//iTest
printf("%x\n",buffer[6]); printf("%x\n",buffer[9]); return0; } 上面程式寫的有問題:應該是
char *p = buffer + 7;
,目標陣列型別與原型別應該保持一致。
#include<stdio.h>
#include<string.h>

int main()
{
  char buffer[1024] = {0,1,2,3,4,5,6,7};
  int iTest = 0x12345678;
  char *p = buffer + 7;
  memcpy(p, &iTest, sizeof
(iTest)); printf("%xn", buffer[6]); printf("%xn", buffer[9]); return 0; }