如何从指针变量计算数组的大小? [英] How to calculate size of array from pointer variable?

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

问题描述

我有数组的指针(在内存中的数组)

我可以根据其指针计算数组的大小吗??????
我实际上不知道内存中的数组在哪里..我只能使用该地址获取指针地址(假设9001),我必须计算数组大小.

谢谢.

i have pointer of array(array which is in memory)

Can i calculate the size of array from its pointer ??????
i dont know actually where is the array in memory..i m only getting pointer adress(suppose 9001) using that adress i have to calculate array size.

Thanks.

推荐答案

如果您所拥有的只是第一个元素的指针,那么您就不能:
If all you have is the pointer to the first element then you can''t:
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() 
  {
  int *parray = &(array[0]);
  int len=sizeof(array)/sizeof(int);
  printf("Length Of Array=%d\n", len);
  len = sizeof(parray);
  printf("Length Of Array=%d\n", len);
  getch();
}

将给出两个不同的值:6和4.
六个是因为array包含6个元素,所以sizeof返回整个数组中的字节数,然后将其除以元素大小(int).
第四是因为sizeof返回指针的大小,而不是所指向的对象.

Will give two different values: 6, and 4.
The six is because array contains 6 elements, so sizeof returns the number of bytes in the whole array, and we divide it by the element size (int).
The four is because sizeof returns the size of the pointer, rather than the object pointed to.


1.如果只有一个指针,则答案为否.
1. If you have only a pointer, the answer is no.
std::size_t getsize(int* parray) {
   return 0; // sorry, no way to tell!
}



2.如果您有一个静态分配的数组,则可以从数组名称中确定元素数.但是,如果是这种情况,并且您不使用C ++功能,则很可能一开始就不需要此功能.



2. If you have s statically allocated array, you can determine the number of elements from the arrays name. However, if that is the case, and you don''t use C++ functionality, then most likely there wouldn''t be a need for this in the first place.

int array[10];
std::size_t length = 10; // big surprise, that number is right in the definition!


或:


or:

int array[] = {4,78,3,7,9,2,56,2,76,23,6,2,1,645};
std::size_t length = sizeof(array)/sizeof(int); // see solution 1



3.或者,使用STL中的容器,例如. G. std::arraystd::vector.这些容器的行为与标准数组非常相似,但是您可以在运行时查询它们的大小,没问题.



3. Alternately, use the containers from the STL, e. g. std::array or std::vector. These containers behave very similar to standard arrays, but you can query their size at runtime, no problem.

std::vector<int> array;
array.pushback(2);
array.pushback(7);
array.pushback(344);
array.pushback(45);
array.pushback(89);
array.pushback(28);
std::size_t length = array.size(); // easy!


如果仅传递给该过程的指针,您不能执行OriginalGriff的
If you have ONLY the pointer that is passed to the procedure, you can''t do OriginalGriff''s solution[^]. You will need to explicitly pass the size of the array to the function. This is not uncommon in C/C++ development. Lot of C library functions have this behavior.


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

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