指针概念

Pointer Conception

本文关键字:指针      更新时间:2023-10-16

这里我得到4225440作为arr[0]的地址;因为它是一个整数数组,所以地址将增加4,所以下一个将是4225444;

现在

  1. 这些地址发生了什么
  2. 如果手动放置其中一个地址,则从其来源显示出荒谬的价值

这是正在讨论的代码

#include <stdio.h>
int arr[10],i,a,*j;
void del(int a);
main()
{
    for(i=0;i<4;i++)
        scanf("%d",&arr[i]);
    j=(int*)4225443;
    for(i=0;i<4;i++)
    {
        printf("n%d ",arr[i]);
        printf(" %d ",&arr[i]);
    }
    printf(" %d ",*j);
}
j=(int*)4225443;
/* ... */
printf(" %d ",*j);

C有话要说:

(C11,6.3.2.3p5)"整数可以转换为任何指针类型。除非前面指定,否则结果是实现定义的,可能没有正确对齐,可能没有指向引用类型的实体,并且可能是陷阱表示。"

在您的情况下,您可以添加到您也违反了别名规则。

most of the CPUs that we use today have either
a 32bit or 64 bit wide bus between the CPU and the memory.
Lets use the 32 bit wide bus for demonstration purposes..
in general, each memory access will be to read (or write) 32 bits,
where the first address of that 32 bits will be an address
that is evenly divisible by 32.
In such a architecture, a 'int' will start on a address 
that is evenly divisible by 32 and be 4 bytes (32bits) long.
in general, when the address of 'something' is NOT 
on a 32 bit address boundary 
(I.E. the address is not evenly divisible by 32) 
then the CPU will:
for read, 
read the whole 32 bits from memory, 
starting at the 32 bit boundary,     
then, within the CPU, 
using the registers and the logic and math operations, 
extract the desired byte.
for write, 
read the whole 32 bits from memory,  
starting at the 32 bit boundary,
then, within the CPU, 
using the registers and logic and math operations, 
modify the desired byte, 
then write the whole 32 bits to memory
In other words, 
accessing memory other than on 32bit boundarys is SLOW.
Unfortunately some CPUs, 
if requested to read/write some value to/from memory
at other than a 32 bit boundary will raise a bus error.
regarding the 'unbelievable' value of the int 
when the second byte of the int is modified...
A int (lets use a little endian architecture) is 4 bytes, 
aligned on a 32 bit boundary 
(I.E. the lowest address of the int is on a 32 bit boundary.)
Lets, for example say the int contains '5' 
then its' representation in memory is 0x00,0x00,0x00,0x05
Then the second byte (address of the int+1) is set to some value,
 for example, say 3,  
Then the int contains 0x000, 0x03, 0x00, 0x05
now, when that int is printed, it will display: 196613
Note: the order of the bytes in memory is somewhat different 
      for a big endian architecture. 

如果值存在,它将打印位于地址4225443的值,否则将产生内存冲突异常。