I am a beginner.
I searched for hours an got confused about how declaring this:
{ {1, 2}, {1, 2, 3} }
Both outer and inner array had known size.
How do I achieve this?
I am a beginner.
I searched for hours an got confused about how declaring this:
{ {1, 2}, {1, 2, 3} }
Both outer and inner array had known size.
How do I achieve this?
Coda
The original post is unclear about when size of the array was known...
If the array's various sizes are known and fixed size at compile time, then the easiest solution would be to use a 2 by 3 array and just ignore one of the elements. Unless you use a C++ vector, it's your responsibily to keep track of the rows, anyway. Note that while this solution wastes an array element, it will take up (slghtly) less memory than the more flexible pointer based approach.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
int a[2][3] = { {1, 2 /*,0*/} // this extra elem. 0-ed by the compiler
, {1, 2, 3} };
const size_t elems_for_i[2] = {2, 3};
for ( size_t i = 0; i < 2; ++i )
for ( size_t j = 0; j < elems_for_i[i]; ++j )
std::cout << "a[" << i << "][" << j << "] = "
<< a[i][j] << '\n';
return 0;
}
You can also do the following, if you don't mind a bit more typing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int a_0[] = {1, 2};
int a_1[] = {1, 2, 3};
int* a[2] = {a_0, a_1}; // int* array
const size_t elems_for_i[2] = {2, 3};
for ( size_t i = 0; i < 2; ++i )
for ( size_t j = 0; j < elems_for_i[i]; ++j )
std::cout << "a[" << i << "][" << j << "] = "
<< a[i][j] << '\n';
return 0;
}
What if I have very large array that contains 10000 elements and vary from range 1 to 100?
Which one is better if I use 10000 pointers or declaring a 10000 by 100 array and ignoring some of the elements?
With a large array, the wasted space could get quite large. So I guess I would go for either the pointer based or vector base solution or, potentially, the int array/int* array.
A more complete answer would depend on what you're using the array for.
I am using it for matching and replacing bytes.
what I am trying to do is declare a large table of byte pattern.
Then loop through the pattern table to match and replace an input stream.
Is the pointer a better idea?