与指针声明数组大小

编程入门 行业动态 更新时间:2024-10-23 12:29:06
本文介绍了与指针声明数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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)

更多推荐

与指针声明数组大小

本文发布于:2023-07-29 00:48:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   大小   声明

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!