简体   繁体   English

C编程中的指针

[英]pointers in C programming

int main(void) {
  int x = 0;
  char* p = (char*) &x;
  int k = 0;
  while (x != -1) {
    *p = -1;
    p = p + 1;
    k = k + 1;
  }
  printf("%d", k);
}

We have already set p to the address of x with char* p = &x; 我们已经用char * p =&x;将p设置为x的地址。 logically, *p=-1 should have replaced the value of x on the first iteration (k=1). 从逻辑上讲,* p = -1应该在第一次迭代(k = 1)时替换了x的值。 In reality (or when I ran the code in VS), it took 4 iterations to complete the value assignment. 在现实中(或当我在VS中运行代码时),花了4次迭代才能完成值分配。 Why? 为什么? and since *p = -1 is executed in every iteration, where did the other three -1s go? 并且因为* p = -1在每次迭代中都执行,所以其他三个-1分别在哪里? Thanks 谢谢

Replace char *p with int *p . char *p替换为int *p Your assignment *p = -1 only writes 1 byte, and an int is 4 bytes. 您的分配*p = -1仅写入1个字节,而int为4个字节。

Your compiler should have generated a warning, as your assignment char *p = &x ; 您的编译器应该已生成警告,因为您的赋值char *p = &x ; is not type safe. 不是类型安全的。

You are using a char size pointer to write into an int size memory space. 您正在使用char大小指针来写入int大小的存储空间。 The only reason it ever gets set to -1 is because of luck. 设置为-1的唯一原因是因为运气好。 -1 happens to be 0xff for a char and 0xffffffff for a int so after writing four 0xff you get one int sized -1. -1恰好是char的0xff和int的0xffffffff,因此在写入四个0xff之后,您将获得一个int大小的-1。

因为(在您的计算机上)一个int是四个字节,但是一个char是1。

x is an int but you declare p as a char * . x是一个整数,但是您将p声明为char * On most modern architectures, an int will be exactly the length of 4 char's... 在大多数现代建筑上,整数将恰好是4个字符的长度。

The address of x initially contains these values: x的地址最初包含以下值:

Byte   1st 2nd 3rd 4th
Value  255 255 255 255

First iteration: 第一次迭代:
*p = -1; * p = -1; -> Address of x 255 255 255 255 -> x 255255255255的地址
p = p + 1; p = p + 1; -> points p to 2nd byte ->将p指向第二个字节

Second iteration: 第二次迭代:
*p = -1; * p = -1; -> Address of x 255 255 255 255 - > x的地址255 255 255 255
p = p + 1; p = p + 1; -> points p to 3rd byte ->将p指向第3个字节

Third iteration: 第三次迭代:
*p = -1; * p = -1; -> Address of x 255 255 255 255 - > x的地址255 255 255 255
p = p + 1; p = p + 1; -> points p to 4th byte ->将p指向第4个字节

4th iteration: 第4次迭代:
*p = -1; * p = -1; -> Address of x 255 255 255 255 - > x的地址255 255 255 255
p = p + 1; p = p + 1; -> points p to 5th byte(outside of x's address) ->将p指向第5个字节(x地址的外部)

From 5th and so forth the value of x will still be -1. 从第5位开始,x的值仍为-1。 I think your program stopped at forth iteration because on the 5th iteration pointer p is already out of bounds. 我认为您的程序在第四次迭代时停止了,因为在第五次迭代中,指针p已经超出范围。 Also, compiler should have given you a warning at compile time because you did not typecast the address of x when assigning it to p. 另外,编译器应该在编译时给您一个警告,因为在将x分配给p时,您没有键入x的地址。 It should have been: 应该是:
char* p = (char*) &x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM