首先,这里有一些代码:
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位系统上是4个字节)?
首先,这里有一些代码:
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位系统上是4个字节)?
当前回答
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
其他回答
不,你不能。编译器不知道指针指向什么。有一些技巧,比如用一个已知的带外值结束数组,然后计算数组的大小直到该值为止,但这不是使用sizeof()。
另一个技巧是Zan提到的,那就是把大小藏在某个地方。例如,如果你在动态分配数组,分配一个比你需要的大一个整型的块,在第一个整型中保存大小,并返回ptr+1作为指向数组的指针。当您需要指针的大小时,可以递减指针并查看存储的值。记住要从头开始释放整个块,而不仅仅是数组。
不,你不能使用sizeof(ptr)来找到ptr所指向的数组的大小。
尽管分配额外的内存(大于数组的大小)会有帮助,如果你想在额外的空间存储长度。
我对这个问题的解决方案是将数组的长度保存到一个struct array中,作为关于数组的元信息。
#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;
}
但是你必须关心你想要存储的数组的正确长度,因为没有办法检查这个长度,就像我们的朋友大量解释的那样。
有一个流行的宏,你可以定义它来查找数组中的元素数量(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
答案是,“不。”
C程序员所做的就是将数组的大小存储在某个地方。它可以是结构的一部分,或者程序员可以欺骗一点,malloc()比要求的更多的内存,以便在数组开始之前存储长度值。