看看我的代码:
#include <stdio.h>
#include <limits.h>
int main (int argc, const char *argv[]) {
typedef unsigned char byte;
byte *pointer;
byte b1=1;
byte b2=2;
int i1 =4;
int i2 =0x12345678;
byte b3=5;
byte b4=6;
byte b5=7;
byte b6=9;
//pointer = &b6;
pointer = (byte*)&i2;
printf("pointer has value %p\n", pointer);
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
*pointer = 255;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
*pointer = 45;
printf("the byte it points to contains %x\n", *pointer);
pointer = pointer + 1;
*pointer = 34;
printf("the byte it points to contains %x\n", *pointer);
//printf("How big is int in this machine? %d\n", INT_MAX);
//insert code here ...
printf (" b1 (%p) = %x\n", &b1, b1);
printf (" b2 (%p) = %x\n", &b2, b2);
printf (" i1 (%p) = %d\n", &i1, i1);
printf (" i2 (%p) = %x\n", &i2, i2);
printf (" b3 (%p) = %x\n", &b3, b3);
printf (" b4 (%p) = %x\n", &b4, b4);
printf (" b5 (%p) = %x\n", &b5, b5);
printf (" b6 (%p) = %x\n", &b6, b6);
return 0;
}
行 * pointer = 255; ,可能是第40行,编译器爆炸,或代码停止工作,说这个 if I make , *pointer = 255 or *pointer = 254
或者在任何其他任意值的情况下,它运行没有任何打击。请告诉我地址的这种行为。
资料来源:Richard Buckland教授,由于他的指导,我正在探索所有这些。
答案 0 :(得分:0)
编译器与此无关。您正在尝试取消引用并分配给无效指针,内存您不拥有。
仅执行++pointer; *pointer = <value>;
是危险的,因为pointer
指向int
类型的单个值,因此++pointer
(或添加除零之外的任何数字)正在移动指向某些内存位置的指针,您可能无权写入甚至访问。因此错误。