c – 在不使用&或*的情况下等待两个指针?
发布时间:2020-12-16 10:51:08 所属栏目:百科 来源:网络整理
导读:我试图理解这段代码的作用(如果它甚至允许的话): int * A;int * B;A = (int *)malloc( size_t somenumber );B = A;// bunch of stuff using B,B++,etc. 我读过的所有内容总是使用引用运算符()或derefernce运算符(*)来表示将指针等同于指针. 这种等同做了什
我试图理解这段代码的作用(如果它甚至允许的话):
int * A; int * B; A = (int *)malloc( size_t somenumber ); B = A; // bunch of stuff using B,B++,etc. 我读过的所有内容总是使用引用运算符(&)或derefernce运算符(*)来表示将指针等同于指针. 这种等同做了什么? 而且,当我最终释放(A)B会发生什么? 解决方法
指针混淆时,图片总是很好:
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 概念: B = A; // Assign B to the value of A (The uninitialized memory) free(A); 毕竟,我认为你可以看到发生了什么. B被赋予A的值,该值是已分配和未初始化的内存块.所以现在你只有两个指向同一区域的指针. 至于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,// 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! } UPDATE 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 所以说明一下: 对于B = * A: int *A; int B; A = malloc(sizeof(int)); *A = 5; B = *A; 这是对A的尊重.所以你只需要拿A指向的东西并将其分配给B,在这种情况下为5 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |