C 传递数组的大小 [英] C sizeof a passed array

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

问题描述

可能的重复:
如何找到sizeof(一个指向一个数组)

我知道 sizeof 运算符在编译时被评估并替换为常量.鉴于此,在程序的不同点传递不同数组的函数如何计算其大小?我可以将它作为参数传递给函数,但如果不是绝对必须,我宁愿不必添加另一个参数.

I understand that the sizeof operator is evaluated and replaced with a constant at compile time. Given that, how can a function, being passed different arrays at different points in a program, have it's size computed? I can pass it as a parameter to the function, but I'd rather not have to add another parameter if I don't absolutely have to.

这里有一个例子来说明我的要求:

Here's an example to illustrate what I'm asking:

#include <stdio.h>
#include <stdlib.h>

#define SIZEOF(a) ( sizeof a / sizeof a[0] )


void printarray( double x[], int );

int main()
{
        double array1[ 100 ];


        printf( "The size of array1 = %ld.\n", SIZEOF( array1 ));
        printf( "The size of array1 = %ld.\n", sizeof array1 );
        printf( "The size of array1[0] = %ld.\n\n", sizeof array1[0] );

        printarray( array1, SIZEOF( array1 ) );

        return EXIT_SUCCESS;
}


void printarray( double p[], int s )
{
        int i;


        // THIS IS WHAT DOESN"T WORK, SO AS A CONSEQUENCE, I PASS THE 
        // SIZE IN AS A SECOND PARAMETER, WHICH I'D RATHER NOT DO.
        printf( "The size of p calculated = %ld.\n", SIZEOF( p ));
        printf( "The size of p = %ld.\n", sizeof p );
        printf( "The size of p[0] = %ld.\n", sizeof p[0] );

        for( i = 0; i < s; i++ )
                printf( "Eelement %d = %lf.\n", i, p[i] );

        return;
}

推荐答案

没有神奇的解决方案.C 不是反射式语言.对象不会自动知道它们是什么.

There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.

但你有很多选择:

  1. 显然,添加一个参数
  2. 将调用包装在宏中并自动添加参数
  3. 使用更复杂的对象.定义一个包含动态数组和数组大小的结构.然后,传递结构的地址.

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

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