与指针声明数组大小 [英] Sizes of arrays declared with pointers

查看:168
本文介绍了与指针声明数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char c[] = "Hello";
char *p = "Hello";

printf("%i", sizeof(c)); \\Prints 6
printf("%i", sizeof(p)); \\Prints 4

我的问题是:

为什么这些打印不同的结果?不 C [] 还声明指向数组的第一个字符(因此应该有大小4,因为它是一个指针)的指针?

Why do these print different results? Doesn't c[] also declare a pointer that points to the first character of the array (and therefore should have size 4, since it's a pointer)?

推荐答案

这听起来像你指针和数组之间的混淆。指针和数组(在这种情况下的char * 的char [] )是的不一样的东西。

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.


  • 阵列烧焦一个[​​SIZE] 表示,在位置值 A 是长度的数组尺寸

  • 指针的char * A; 表示,在位置值 A 是一个指向一个字符。这可以用指针运算结合起来,表现得像一个数组(例如, A [10] 是过去无论 A 点)

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

在内存中,它看起来像这样(从常见问题):

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

这很容易混淆了指针和数组之间的区别,因为在很多情况下,一个数组引用衰变的指针到它的第一个元素。这意味着,在许多情况下,(当传递给函数调用如)阵列成为指针。如果您想了解更多,请的C常见问题本节详细介绍了。

一个重大现实不同的是,编译器知道数组有多长。使用上述的例子:

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

这篇关于与指针声明数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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