繁体   English   中英

如何找到“sizeof”(指向数组的指针)?

[英]How to find the 'sizeof' (a pointer pointing to an array)?

首先,这里有一些代码:

int main() 
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", sizeof(days));
    printf("%u\n", sizeof(ptr));

    return 0;
}

有没有办法找出ptr指向的数组的大小(而不是仅仅给出它的大小,在 32 位系统上是四个字节)?

不,你不能。 编译器不知道指针指向什么。 有一些技巧,比如用已知的带外值结束数组,然后计算大小直到该值,但这不是使用sizeof()

另一个技巧是Zan提到的一个技巧,即将尺寸存储在某处。 例如,如果您正在动态分配数组,请分配一个比您需要的大一个 int 的块,将大小存储在第一个 int 中,然后返回ptr+1作为指向数组的指针。 当您需要大小时,减小指针并查看隐藏的值。 请记住从头开始释放整个块,而不仅仅是数组。

答案是不。”

C 程序员所做的是将数组的大小存储在某处。 它可以是结构的一部分,或者程序员可以作弊,然后malloc()比请求的内存更多,以便在数组开始之前存储长度值。

对于动态数组( malloc或 C++ new ),您需要存储其他人提到的数组的大小,或者可能构建一个数组管理器结构来处理添加、删除、计数等。不幸的是,C 并没有做到这一点C ++,因为您基本上必须为要存储的每种不同的数组类型构建它,如果您需要管理多种类型的数组,这会很麻烦。

对于静态数组,例如您的示例中的那个,有一个用于获取大小的通用宏,但不建议这样做,因为它不检查参数是否真的是静态数组。 该宏在实际代码中使用,例如在 Linux 内核头文件中,尽管它可能与下面的稍有不同:

#if !defined(ARRAY_SIZE)
    #define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif

int main()
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", ARRAY_SIZE(days));
    printf("%u\n", sizeof(ptr));
    return 0;
}

您可以出于对此类宏保持警惕的原因进行谷歌搜索。 当心。

如果可能的话,C++ 标准库,比如vector,它更安全、更容易使用。

有一个使用 C++ 模板的干净解决方案,无需使用sizeof() 以下getSize()函数返回任何静态数组的大小:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

这是一个带有foo_t结构的示例:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

struct foo_t {
    int ball;
};

int main()
{
    foo_t foos3[] = {{1},{2},{3}};
    foo_t foos5[] = {{1},{2},{3},{4},{5}};
    printf("%u\n", getSize(foos3));
    printf("%u\n", getSize(foos5));

    return 0;
}

输出:

3
5

正如所有正确答案所述,您无法仅从数组的衰减指针值中获取此信息。 如果衰减的指针是函数接收的参数,则必须以其他方式提供原始数组的大小,以便函数知道该大小。

这是一个与迄今为止提供的不同的建议,它将起作用:改为传递指向数组的指针。 此建议类似于 C++ 样式建议,只是 C 不支持模板或引用:

#define ARRAY_SZ 10

void foo (int (*arr)[ARRAY_SZ]) {
    printf("%u\n", (unsigned)sizeof(*arr)/sizeof(**arr));
}

但是,这个建议对您的问题来说有点愚蠢,因为该函数被定义为确切知道传入的数组的大小(因此,几乎不需要在数组上使用 sizeof)。 不过,它所做的是提供某种类型的安全性。 它将禁止您传入不需要大小的数组。

int x[20];
int y[10];
foo(&x); /* error */
foo(&y); /* ok */

如果该函数应该能够对任何大小的数组进行操作,那么您必须将大小作为附加信息提供给该函数。

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

但是你有很多选择:

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

对于这个具体的例子,是的,如果你使用 typedefs(见下文)。 当然,如果你这样做,你也可以使用 SIZEOF_DAYS,因为你知道指针指向什么。

如果您有一个 (void *) 指针,如 malloc() 等返回的那样,那么,不,无法确定指针指向的数据结构,因此无法确定其大小。

#include <stdio.h>

#define NUM_DAYS 5
typedef int days_t[ NUM_DAYS ];
#define SIZEOF_DAYS ( sizeof( days_t ) )

int main() {
    days_t  days;
    days_t *ptr = &days; 

    printf( "SIZEOF_DAYS:  %u\n", SIZEOF_DAYS  );
    printf( "sizeof(days): %u\n", sizeof(days) );
    printf( "sizeof(*ptr): %u\n", sizeof(*ptr) );
    printf( "sizeof(ptr):  %u\n", sizeof(ptr)  );

    return 0;
} 

输出:

SIZEOF_DAYS:  20
sizeof(days): 20
sizeof(*ptr): 20
sizeof(ptr):  4

你可以这样做:

int days[] = { /*length:*/5, /*values:*/ 1,2,3,4,5 };
int *ptr = days + 1;
printf("array length: %u\n", ptr[-1]);
return 0;

我对这个问题的解决方案是将数组的长度保存到结构数组中,作为数组的元信息。

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

struct Array
{
    int length;

    double *array;
};

typedef struct Array Array;

Array* NewArray(int length)
{
    /* Allocate the memory for the struct Array */
    Array *newArray = (Array*) malloc(sizeof(Array));

    /* Insert only non-negative length's*/
    newArray->length = (length > 0) ? length : 0;

    newArray->array = (double*) malloc(length*sizeof(double));

    return newArray;
}

void SetArray(Array *structure,int length,double* array)
{
    structure->length = length;
    structure->array = array;
}

void PrintArray(Array *structure)
{       
    if(structure->length > 0)
    {
        int i;
        printf("length: %d\n", structure->length);
        for (i = 0; i < structure->length; i++)
            printf("%g\n", structure->array[i]);
    }
    else
        printf("Empty Array. Length 0\n");
}

int main()
{
    int i;
    Array *negativeTest, *days = NewArray(5);

    double moreDays[] = {1,2,3,4,5,6,7,8,9,10};

    for (i = 0; i < days->length; i++)
        days->array[i] = i+1;

    PrintArray(days);

    SetArray(days,10,moreDays);

    PrintArray(days);

    negativeTest = NewArray(-5);

    PrintArray(negativeTest);

    return 0;
}

但是你必须关心设置你要存储的数组的正确长度,因为没有办法检查这个长度,就像我们的朋友大量解释的那样。

不,您不能使用sizeof(ptr)来查找数组ptr指向的大小。

如果您想将长度存储在额外的空间中,虽然分配额外的内存(超过数组的大小)会很有帮助。

int main() 
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", sizeof(days));
    printf("%u\n", sizeof(ptr));

    return 0;
}

days[] 的大小为 20,即没有元素 * 数据类型的大小。 而指针的大小是 4 无论它指向什么。 因为指针通过存储它的地址来指向其他元素。

这就是我个人在代码中的做法。 我喜欢让它尽可能简单,同时仍然能够获得我需要的值。

typedef struct intArr {
    int size;
    int* arr; 
} intArr_t;

int main() {
    intArr_t arr;
    arr.size = 6;
    arr.arr = (int*)malloc(sizeof(int) * arr.size);

    for (size_t i = 0; i < arr.size; i++) {
        arr.arr[i] = i * 10;
    }

    return 0;
}
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>

#define array(type) struct { size_t size; type elem[0]; }

void *array_new(int esize, int ecnt)
{
    size_t *a = (size_t *)malloc(esize*ecnt+sizeof(size_t));
    if (a) *a = ecnt;
    return a;
}
#define array_new(type, count) array_new(sizeof(type),count)
#define array_delete free
#define array_foreach(type, e, arr) \
    for (type *e = (arr)->elem; e < (arr)->size + (arr)->elem; ++e)

int main(int argc, char const *argv[])
{
    array(int) *iarr = array_new(int, 10);
    array(float) *farr = array_new(float, 10);
    array(double) *darr = array_new(double, 10);
    array(char) *carr = array_new(char, 11);
    for (int i = 0; i < iarr->size; ++i) {
        iarr->elem[i] = i;
        farr->elem[i] = i*1.0f;
        darr->elem[i] = i*1.0;
        carr->elem[i] = i+'0';
    }
    array_foreach(int, e, iarr) {
        printf("%d ", *e);
    }
    array_foreach(float, e, farr) {
        printf("%.0f ", *e);
    }
    array_foreach(double, e, darr) {
        printf("%.0lf ", *e);
    }
    carr->elem[carr->size-1] = '\0';
    printf("%s\n", carr->elem);

    return 0;
}
 #define array_size 10

 struct {
     int16 size;
     int16 array[array_size];
     int16 property1[(array_size/16)+1]
     int16 property2[(array_size/16)+1]
 } array1 = {array_size, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

 #undef array_size

array_size 传递给size变量:

#define array_size 30

struct {
    int16 size;
    int16 array[array_size];
    int16 property1[(array_size/16)+1]
    int16 property2[(array_size/16)+1]
} array2 = {array_size};

#undef array_size

用法是:

void main() {

    int16 size = array1.size;
    for (int i=0; i!=size; i++) {

        array1.array[i] *= 2;
    }
}

在字符串中,末尾有一个'\\0'字符,因此可以使用strlen等函数获取字符串的长度。 例如,整数数组的问题是您不能使用任何值作为结束值,因此一种可能的解决方案是寻址数组并使用NULL指针作为结束值。

#include <stdio.h>
/* the following function will produce the warning:
 * ‘sizeof’ on array function parameter ‘a’ will
 * return size of ‘int *’ [-Wsizeof-array-argument]
 */
void foo( int a[] )
{
    printf( "%lu\n", sizeof a );
}
/* so we have to implement something else one possible
 * idea is to use the NULL pointer as a control value
 * the same way '\0' is used in strings but this way
 * the pointer passed to a function should address pointers
 * so the actual implementation of an array type will
 * be a pointer to pointer
 */
typedef char * type_t; /* line 18 */
typedef type_t ** array_t;
int main( void )
{
    array_t initialize( int, ... );
    /* initialize an array with four values "foo", "bar", "baz", "foobar"
     * if one wants to use integers rather than strings than in the typedef
     * declaration at line 18 the char * type should be changed with int
     * and in the format used for printing the array values 
     * at line 45 and 51 "%s" should be changed with "%i"
     */
    array_t array = initialize( 4, "foo", "bar", "baz", "foobar" );

    int size( array_t );
    /* print array size */
    printf( "size %i:\n", size( array ));

    void aprint( char *, array_t );
    /* print array values */
    aprint( "%s\n", array ); /* line 45 */

    type_t getval( array_t, int );
    /* print an indexed value */
    int i = 2;
    type_t val = getval( array, i );
    printf( "%i: %s\n", i, val ); /* line 51 */

    void delete( array_t );
    /* free some space */
    delete( array );

    return 0;
}
/* the output of the program should be:
 * size 4:
 * foo
 * bar
 * baz
 * foobar
 * 2: baz
 */
#include <stdarg.h>
#include <stdlib.h>
array_t initialize( int n, ... )
{
    /* here we store the array values */
    type_t *v = (type_t *) malloc( sizeof( type_t ) * n );
    va_list ap;
    va_start( ap, n );
    int j;
    for ( j = 0; j < n; j++ )
        v[j] = va_arg( ap, type_t );
    va_end( ap );
    /* the actual array will hold the addresses of those
     * values plus a NULL pointer
     */
    array_t a = (array_t) malloc( sizeof( type_t *) * ( n + 1 ));
    a[n] = NULL;
    for ( j = 0; j < n; j++ )
        a[j] = v + j;
    return a;
}
int size( array_t a )
{
    int n = 0;
    while ( *a++ != NULL )
        n++;
    return n;
}
void aprint( char *fmt, array_t a )
{
    while ( *a != NULL )
        printf( fmt, **a++ );   
}
type_t getval( array_t a, int i )
{
    return *a[i];
}
void delete( array_t a )
{
    free( *a );
    free( a );
}

大多数实现都会有一个函数告诉您使用malloc()calloc()分配的对象的保留大小,例如 GNU 有malloc_usable_size()

但是,这将返回反转块的大小,该大小可能大于malloc() / realloc()的值。


有一个流行的宏,您可以定义它来查找数组中的元素数量(Microsoft CRT 甚至为它提供了名称为_countof的 OOB):

#define countof(x) (sizeof(x)/sizeof((x)[0]))

然后你可以写:

int my_array[] = { ... some elements ... };
printf("%zu", countof(my_array)); // 'z' is correct type specifier for size_t

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM