数组指针如何存储其大小? [英] How does an array pointer store its size?

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

问题描述

#include "stdio.h"

#define COUNT(a) (sizeof(a) / sizeof(*(a)))

void test(int b[]) {
  printf("2, count:%d\n", COUNT(b));
}

int main(void) {
  int a[] = { 1,2,3 };

  printf("1, count:%d\n", COUNT(a));
  test(a);

  return 0;
}

结果很明显:

1, count:3
2, count:1

我的问题:

  1. 声明"a"时存储的长度(计数/大小)信息在哪里?
  2. 当将"a"传递给test()函数时,为什么长度(计数/尺寸)信息丢失了?

推荐答案

在C语言中没有数组指针"之类的东西.

There's no such thing as "array pointer" in C language.

大小未存储在任何地方. a不是指针,a是类型为int[3]的对象,这是编译器在编译时众所周知的事实.因此,当您要求编译器在编译时计算sizeof(a) / sizeof(*a)时,编译器就会知道答案是3.

The size is not stored anywhere. a is not a pointer, a is an object of type int[3], which is a fact well known to the compiler at compile time. So, when you ask the compiler to calculate sizeof(a) / sizeof(*a) at compile time the compiler knows that the answer is 3.

当您将a传递给函数时,您有意要求编译器将数组类型转换为指针类型(因为您已将函数参数声明为指针).对于指针,您的sizeof表达式产生完全不同的结果.

When you pass your a to the function you are intentionally asking the compiler to convert array type to pointer type (since you declared the function parameter as a pointer). For pointers your sizeof expression produces a completely different result.

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

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