看看我的代码:
#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 教授,由于他的指导,我正在探索所有这些。
最佳答案
编译器与此无关。您正在尝试取消引用并分配给一个无效的指针,即您不拥有的内存。
只做++pointer; *pointer = <value>;
是危险的 pointer
指向 int
类型的单个值,所以++pointer
(或添加除零之外的任何数字)正在将指针移动到您可能无权写入甚至访问的某个内存位置。因此出现了错误。
关于当我尝试更改某些地址值时,C 程序停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794101/