Changes

Jump to: navigation, search

C/C++ FAQ

1,287 bytes added, 20:46, 19 November 2012
no edit summary
Example explanation: A stack has numbers 15 10 5 on it and an array allocated to 3 indexes (with values 0, 1, 2) to match the number of Nodes. If a person adds 1 more data to the Stack (push(20))then the array would have to be deleted and reallocated, defeating the purpose of the stack in the first place.
<br>'''Submitted by:''' Team 6 <br><br>
'''Q:''' How to get size of an array without storing the size anywhere? <br>
'''A:''' There are several ways to get the length of an array without explicitly knowing its length. The C method is as follows
<source lang="cpp">
#define SIZEOF_ARRAY( a ) (sizeof( a ) / sizeof( a[ 0 ] ))
 
</source>
 
The above define macro can be called to find the size of an array in a C manner. This function exists in the std namespace.<br>
 
One could also use the below code for a more effective (but c++ only) solution.
 
<source lang="cpp">
 
#include <iostream> using namespace std; template <typename T, size_t N> inline size_t SizeOfArray( const T(&)[ N ] ) { return N; } int main() { const char s[] = "Hello world!";
 
cout << "s[] is " << SizeOfArray( s );
 
}
 
</source>
 
The good thing about the above method is not only its improved efficiency (most compilers will optimize the template function out of existance upon compilation) but the fact that it will not work with a pointer to an array, such as
 
<source lang="cpp">
 
const char* s = "Hello world!"; cout << "s is " << SizeOfArray( s )
 
</source>
 
Lastly, with C++11 there is an even better method of doing this: std::extent. More info on this trait class can be found [http://www.cplusplus.com/reference/std/type_traits/extent/ here]

Navigation menu