是用C种不同的光标之间的差 [英] what is the difference between different kinds of pointer in C

查看:114
本文介绍了是用C种不同的光标之间的差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我们可以定义不同类型的指针,如:

In C language,we can define different kinds of pointer such as:


  • 为int * P

  • 的char * P
    所有这些都具有相同的大小4个字节或8个字节。所有的人都可以被用作用于与printf(%S,p)的一个参数,所以编译它们之间如何区分?

推荐答案

这是所有关于静态类型检查和指针运算。
也许这是最好看一个具体的例子来说明。

It's all about static type checking and pointer arithmetics. Perhaps it's best illustrated by looking at a concrete example.

考虑一下:

#include <stdio.h>

int main( int argc, char *argv[] )
{
   char x[10];

   char *p0       = &x[0];  /* ok */
   int  *p1       = &x[0];  /* <- type checking, warning #1 */
   char (*p2)[10] = &x;     /* ok */
   int  (*p3)[10] = &x;     /* <- type checking, warning #2 */

   (void)printf( "sizeof(char): %ld\n", sizeof( char ));
   (void)printf( "sizeof(int):  %ld\n", sizeof( int ));

   (void)printf( "p0: %p, p0+1: %p\n", (void*)p0, (void*)( p0+1 ));
   (void)printf( "p1: %p, p1+1: %p\n", (void*)p1, (void*)( p1+1 ));
   (void)printf( "p2: %p, p2+1: %p\n", (void*)p2, (void*)( p2+1 ));
   (void)printf( "p3: %p, p3+1: %p\n", (void*)p3, (void*)( p3+1 ));

   return 0;
}

重要提示:以 -Wall 编译(的gcc -o -Wall测试test.c的

该程序可以编译,但你会得到关于不兼容的指针类型两次警告,这是正确的。

The program will compile, but you'll get two warnings about incompatible pointer types, and rightly so.

% gcc -Wall -o test test.c
test.c: In function ‘main’:
test.c:9:21: warning: initialization from incompatible pointer type [enabled by default]
    int  *p1       = &x[0];  /* <- type checking, warning #1 */
                     ^
test.c:11:21: warning: initialization from incompatible pointer type [enabled by default]
    int  (*p3)[10] = &x;     /* <- type checking, warning #2 */
                     ^

现在运行程序:

% ./test 
sizeof(char): 1
sizeof(int):  4
p0: 0x7fff9f6dc5c0, p0+1: 0x7fff9f6dc5c1  # + 1 char
p1: 0x7fff9f6dc5c0, p1+1: 0x7fff9f6dc5c4  # + 1 int (4 bytes here)
p2: 0x7fff9f6dc5c0, p2+1: 0x7fff9f6dc5ca  # + 10 chars
p3: 0x7fff9f6dc5c0, p3+1: 0x7fff9f6dc5e8  # + 10 ints (40 bytes here)

在这里,你可以观察指针算术的影响:尽管所有4的指针被初始化为相同的值,同样的操作产生完全不同的结果。

Here you can observe the impact on pointer arithmetics: although all 4 pointers were initialized to the same value, the same operation yields completely different results.

这篇关于是用C种不同的光标之间的差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆