how can i know what the size of array meaning
i[n]
how i can know what is the n is (total the end)
Printable View
how can i know what the size of array meaning
i[n]
how i can know what is the n is (total the end)
It is not pratical, but works with static arrays. You have n=(sizeof(yourArray)/sizeof(int)). But if you have an static array you already know the size. My suggestion is that you use the vector class.
If you are using a static array ( i [n] ) and you want the number of elements (n), use sizeof.
If, however, you want the offset of the last element, use :Code:int I [n];
int SizeOfI
int SizeOf sizeof I;
Using vectors or deques is better. They dont overfill, you cant write past the end, - dont let me go on.Code:int I [n];
int SizeOfI
int SizeOf sizeof I - 1 ;
If you want to learn vectors, strings (dont use char arrays) go to http://www.cppreference.com .
There's nothing wrong with char arrays if you use them correctly. In fact, some functions take them as a parameter, which makes it difficult to use strings.Quote:
Generally you will pass the size of the array to the function you are using it in:
If you don't know what the length of the string will be (a user is inputting it, for example) then using a std::string might be better.Code:int somefunc(char* str,int n)
{
//...
}
>if you use them correctly
There you go. Many people don't know how to use them correctly, either through lack of experience or lack of proper education (or stupidity. I hate to say it, but it's true). This is why C++ discourages the use of low level constructs, they are too dangerous for most of the plebs out there.
:)Quote:
In fact, some functions take them as a parameter, which makes it difficult to use strings.
[code]
std::string szString;
char LameCharString [60];
LameCharString = szString.c_str();
{/code]
Like I said, not impossible, but slightly more difficult. Although c_str() returns a const c-string :D There's two other ways:
std::string::data()
Returns a const char* without a '\0' terminator
std::string::copy(char* buf, size_type buf_size)
returns a char* without a '\0' and copies up to buf_size characters
std::string::copy(char* buf, size_type buf_size, size_type idx)
same as above, but starts copying at the index idx
See if you need a non-const c-string then you have to not only call the copy function, but append a '\0' at the end...Also if you use the second form of copy, it may throw an exception if you use an invalid index for idx (one that is greater than string::length())