how to get the length of a array?
조회 수: 11 (최근 30일)
이전 댓글 표시
I know mxGetM and mxGetN can get the row and col,and its parameter is a array name or a pointer.
But,I know when a array name act as a function parameter, it will behave just a pointer. for exmaple,
#
include <iostream>
using namespace std ;
int GetM(int* array)
{
return sizeof(array)/sizeof(array[0]) ;
}
int main()
{
int a[3] = {1,2,3} ;
cout<<GetM(a)<<endl ;
}
in this example ,GetM(a) return 1,not 3.so,I want to know how to realize matlab function mxGetM or how to get the length of a array. thanks a lot!
댓글 수: 0
채택된 답변
Walter Roberson
2014년 1월 5일
Array names are pointers in C++.
Your GetM code is dividing the size of the pointer by the size of the first element of the array; as it is an array of int, sizeof() the first element would be sizeof(int) so the "1" is reflecting the integer truncated division of the size of a pointer by the size of an int.
To get the length of a C++ array in C++, make the array an object of a class that records the length when the object was created and makes the length available as a property of the class.
To use C++ to get the length of a MATLAB array, call the appropriate mx* routine. MATLAB arrays point to a descriptor of the array, including each of the dimensions, and including a pointer to the actual data block. This is not the way other C++ arrays are stored (unless they have been designed for compatibility with MATLAB.)
댓글 수: 0
추가 답변 (1개)
James Tursa
2014년 1월 5일
Pass the length of the "array" as part of the argument list. You can't get this info by simply examining the "array" pointer itself as you are attempting. "a" is of type "array of 3 int's", but "array" is of type "pointer to int".
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call C++ from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!