何时应该数组名被视为一个指针,当它只是重新present数组本身? [英] When should an array name be treated as a pointer and when does it just represent the array itself?

查看:135
本文介绍了何时应该数组名被视为一个指针,当它只是重新present数组本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看完这本书后,做了一个测试程序,结果变成了混乱:

 的#include<&stdio.h中GT;
    INT主要(无效)
    {
        字符文本[] =你好!;        的printf(的sizeof(文本):%d个的sizeof(文本+ 2):%d个的sizeof(文[0]):%d个\\ N(INT)的sizeof(文本),sizeof的(文本+ 2)的sizeof(文[0]));
        的printf(文本:%P的sizeof(文本):%D&放大器;文本:%P的sizeof(安培;文本)数:%d \\ n,文字的sizeof(文字),放大器;文字的sizeof(安培;文) );
        的printf(文字+ 1:%P和;文字+ 1:%P \\ N,文字+ 1,&安培;文字+ 1);        返回0;
    }

结果:

 的sizeof(文本):7的sizeof(文本+ 2):4的sizeof(文[0]):1
文本:0xbfc8769d的sizeof(文本):7和;文字:0xbfc8769d的sizeof(安培;文本):4
文字+ 1:0xbfc8769e&功放;文字+ 1:0xbfc876a4

是什么让我感到困惑是:


  1. 为什么'的sizeof(文本)'的值是7,而'的sizeof(文本+ 2)'是4

  2. 什么是'文本'和'&放大器;文本'之间的区别?


解决方案

重要提示:数组不是指针

他们降解,如果在预期的指针上下文使用它们的指针。


  • 的sizeof(文本)得到阵列在一个整体,因此输出7;

  • 的sizeof(文本+ 2)指针算法让数组降解为指针

  • 的sizeof(文[0])当然元素的大小

  • 的sizeof;指针数组的(放文)尺寸。显然是一个指针太

使用地址的阵列上运行明确检索指向特定类型的数组(你的情况的char [7] 。该指针具有相同的地址,但不同类型的比对指针降级阵列。

所以之间的差异文字+ 1 &放大器;文字+ 1 也应该是显而易见的。第一逐个元素递增字符指针 - >指向后面的第一个一个元件。第二点,所述第二后面的第一个7元素炭阵列

I just made a test program after reading the book and the result turned out confusing:

    #include <stdio.h>
    int main(void)
    {
        char text[] = "hello!";

        printf("sizeof(text):%d  sizeof(text+2):%d  sizeof(text[0]):%d \n",(int)sizeof(text), sizeof(text+2), sizeof(text[0]));
        printf("text:%p sizeof(text):%d      &text:%p sizeof(&text):%d \n",text, sizeof(text), &text, sizeof(&text));
        printf("text+1:%p  &text+1:%p  \n", text+1, &text+1);

        return 0;
    }

The result:

sizeof(text):7  sizeof(text+2):4  sizeof(text[0]):1 
text:0xbfc8769d sizeof(text):7      &text:0xbfc8769d sizeof(&text):4 
text+1:0xbfc8769e  &text+1:0xbfc876a4 

What makes me feel confused are:

  1. why the value of 'sizeof(text)' is 7 whereas 'sizeof(text+2)' is 4
  2. what's the difference between 'text' and '&text'?

解决方案

Important: arrays are not pointer

they degrade to pointer if using them in contexts that expect a pointer.

  • sizeof(text) gets the array at a whole so it outputs 7;
  • sizeof(text+2) pointer arithmetic let the array degrade to a pointer
  • sizeof(text[0])size of an element of course
  • sizeof(&text) size of the pointer to the array. obviously a pointer too

using the address operates on an array explicitly retrieves a pointer to an array of that specific type (in your case char[7]. that pointer has the same address but a different type than a to-pointer-degraded array.

so the difference between text+1 and &text+1 should also be obvious. the first one increments the char pointer by one element --> points one element behind the first one. the second points to the second 7-element-char-array behind the first one.

这篇关于何时应该数组名被视为一个指针,当它只是重新present数组本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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