hen*_*nje 4 c pointers language-lawyer
我最近在stackoverflow上遇到了一些代码,其中指针指向用于更改已分配内存的指针.在检查代码时,我错误地将一个&符添加到指针,因此创建一个指向指针的指针仍然是编译器愉快地编译并发生运行时错误.举个例子
#include <stdio.h>
void func(int **p) {
printf("Pointer is at %p\n", p);
}
int main(void) {
int *p = 0;
func(p);
func(&p);
int **pp = &p;
func(&pp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我确实理解C对指针的限制明显低于C++,并char *buf = malloc(SIZE)允许在C++中不允许使用.我觉得它很方便,因为它在C中发生了很多.
尽管如此,我认为引用的数量是一个很大的错误来源,我想知道为什么人们可能允许这样做,特别是因为int不同int*.此外,我想知道C标准是否说明了这一点.
编辑 我在ideone.com下编译它可能不会显示警告.我的本地clang编译器以及gcc都会发出警告.不过,为什么当他们代表不同的事情时,他们只是警告.
PS,我觉得在过去的六年中应该问过这样的事情.如果这个重复,我很抱歉找不到.
转换不合法.更确切地说,没有隐式转换从int*到int**,或者int***到int**.试图传递一个int*或一个int***需要int**参数的函数是一个约束违规 ; 任何符合标准的编译器都必须诊断它.(诊断消息可能是非致命警告.)
当我使用gcc编译代码时,即使使用默认选项(这会使gcc不符合),我会收到几个警告:
c.c: In function ‘func’:
c.c:4:3: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int **’ [-Wformat=]
printf("Pointer is at %x\n", p);
^
c.c: In function ‘main’:
c.c:9:3: warning: passing argument 1 of ‘func’ from incompatible pointer type [enabled by default]
func(p);
^
c.c:3:6: note: expected ‘int **’ but argument is of type ‘int *’
void func(int **p) {
^
c.c:12:3: warning: passing argument 1 of ‘func’ from incompatible pointer type [enabled by default]
func(&pp);
^
c.c:3:6: note: expected ‘int **’ but argument is of type ‘int ***’
void func(int **p) {
^
Run Code Online (Sandbox Code Playgroud)
我不知道为什么意思不抱怨它(http://ideone.com/uzeXur).
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |