在不使用&或*的情况下等待两个指针?

Eli*_*sey 3 c pointers

我试图理解这段代码的作用(如果它甚至允许的话):

int * A;
int * B;
A = (int *)malloc( size_t somenumber );
B = A;

// bunch of stuff using B, B++, etc.
Run Code Online (Sandbox Code Playgroud)

我读过的所有内容总是使用引用运算符(&)或derefernce运算符(*)来显示将指针等同于指针.

这种等同做了什么?

而且,当我最终free(A)发生什么事情B?

das*_*ght 7

这不等于两个指针,它是一个指针赋值.一旦

B = A;
Run Code Online (Sandbox Code Playgroud)

执行时,两个指针都指向相同的内存区域:访问*B与访问完全相同*A,B[i]变得等同于A[i]等等.

请注意,释放A叶子B 悬空,反之亦然.换句话说,在打电话之后

free(A);
Run Code Online (Sandbox Code Playgroud)

访问*B成为未定义的行为.


Mik*_*ike 6

指针混淆时,图片总是很好:

int * A; // create a pointer to an int named "A"
int * B; // create a pointer to an int named "B"
A = (int *)malloc( size_t somenumber ); // Allocate A some memory, now B is an 
                                        // uninitialized pointer; A is initialized,
                                        // but just to uninitialized memory
Run Code Online (Sandbox Code Playgroud)

概念:

在此输入图像描述

B = A; // Assign B to the value of A (The uninitialized memory)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

free(A);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

毕竟,我认为你可以看到发生了什么.B被赋予A的值,该值是已分配和未初始化的内存块.所以现在你只有两个指向同一区域的指针.

关于这个free()问题,你可以看到,当你打电话给free(A);你的时候A和B都指向同一个区域,那里就没有任何东西可以分配到你的程序了.这就是为什么在调用free()它时将指针设置为好的原因NULL.

现在回到你最初的问题.如果你想检查两个指针​​是==:

int * A; // create a pointer to an int named "A"
int * B; // create a pointer to an int named "B"
A = (int *)malloc( size_t somenumber ); // Allocate A some memory, now B is an 
                                        // uninitialized pointer; A is initialized,
                                        // but just to uninitialized memory

if(B == A){
   // The pointers are pointing to the same thing!
}
if(*B == *A){
   // The values these pointers are pointing to is the same!
}
Run Code Online (Sandbox Code Playgroud)

更新
因此,为了回答您更新的问题,我们需要更改定义B.

int *A;  // A is a pointer to an int
int **B; // B is a pointer to a pointer to an int
B = &A;  // B is now pointing to A
Run Code Online (Sandbox Code Playgroud)

所以说明一下:

在此输入图像描述

用于B=*A:

int *A;
int B;
A = malloc(sizeof(int));
*A = 5;
B = *A;
Run Code Online (Sandbox Code Playgroud)

这是一种尊重A.因此,你只需要拿A指向并分配给它B,在这种情况下为5