fill_n() is not letting change variable value - c++

I am using fill_n() function to initialize my array values, but then I cannot change the values of the array, it is always the initial value.
Can someone explain me why is that?
#include<iostream>
#include<ctime>
int main(){
//Matrix
int m[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
int v[3] = {5,6,7};
int result[3];// = {0,0,0};
int n = 0, i, j;
std::fill_n(result,sizeof(result),0);
clock_t time = clock();
while(n<1000){
n++;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
result[j] = result[j]+(v[i]*m[j][i]); //changing the values here.
}
}
}
time = clock() - time;
for(i=0;i<3;i++){
std::cout<<result[i]<<"\n";
}
std::cout<<"Execution time: "<<((float)time)/CLOCKS_PER_SEC<<"\n";
return 0;
}
The output of the code is always 0.

By std::fill_n(result,sizeof(result),0); you are asking to fill the first sizeof(result) elements by 0.
However, only 3 elements are available in result. Thus you wrote out-of-bound and led to undefined behavior. You should write std::fill_n(result, sizeof(result) / sizeof(result[0]), 0); instead.
Note that sizeof(result) returns size of result in bytes, not in elements.

sizeof(result) returns the number of bytes held by the variable result. Since result is an array of 3 ints, its size in memory is 3 * sizeof(int), which (unless sizeof(int) is 1) much greater than 3. Thus you are writing pass array bounds and incurring undefined behavior.
The actual way to calculate the size would be to divide the entire size of result by its element type. That is, sizeof(result) / sizeof(int).
If you want to initialize each element to 0, a simpler way to do it would be to value-initialize the array:
int result[3]{}; // or = {} (pre C++11)

Number of elements (or size) of an array of type type would be sizeof(array) / sizeof(type). Second argument required for fill_n is the number of elements to fill a container (in your case, an array of type int) and not the size of an array in bytes. Naturally, sizeof(array) returns sizeof(type) times number of elements.

Related

Array larger than specified size in C++ [duplicate]

This question already has answers here:
c++ sizeof(array) return twice the array's declared length
(6 answers)
How do I find the length of an array?
(30 answers)
Closed 4 years ago.
When testing an array like this:
float test [3] = {1, 2, 3};
cout << "Test size: " << sizeof(test) << endl;
The size shown by the print statement is 12. Similarly, when I made the size 12, the number of elements in the array was 47. Isn't this the correct way to specify the size of an array in C++?
sizeof doesn't return the number of elements in the array, it returns the memory size in bytes. Since your array contains three regular integers, and integers are 4 bytes in size, that's 3 * 4 == 12 bytes.
To get the length of the array, you have a few options:
Option 1
int size = sizeof(test) / sizeof(test[0]);
What that does is get the size of the array (which is 12 bytes) then divides that by the size of a single element (which is 4 bytes). Obviously 12 / 4 == 3.
Option 2
As pointed out by #PaulMcKenzie, if you're able to use C++17 you can use std::size. That makes it very easy because you can just do this:
int size = std::size(test);
Option 3 (Not recommended)
int size = *(&test + 1) - test;
Which is a clever hack using pointers, explained here. Will result in undefined behaviour and may break, depending on the compiler and its optimisations.
If you want the more efficient way of calculating the number of elements in an array, you could use templates.
template<typename T, std::size_t Size>
std::size_t GetArrLength(T(&)[Size]) { return Size; }
If we call it as such:
float test[3] = {1,2,3};
GetArrLength(test);
The compiler will try to deduce the template parameters. For the parameter type to match what you're passing, T must be float and size must be 3 (making the parameter a reference to an array of 3 floats).
You must use following way to get the actual size of array you requires.
int size = sizeof(test)/sizeof(test[0]);
sizeof() actually returns no. of bytes. So, you get the no. of bytes in your array object. To get actually the no. of elements, we need to divide it by the size of an element there. For example, here sizeof(float)
You need to divide the single element size to get the array size.
int sz = sizeof(test) / sizeof(test[0]);
cout << "test size: " << sz << endl;
This will work :
size_t n = sizeof(test)/sizeof(test[0]);
size_t is a type guaranteed to hold any array index, so use size_t.
The standard library has a type trait for this purpose.
#include <type_traits>
#include <iostream>
int main()
{
float test [3] = {1, 2, 3};
std::cout
<< std::extent<decltype(test)>::value
<< '\n';
}

Why would my array would be filled out to zero, when I initialised it to -1

#include<iostream>
using namespace std;
long long int memo[20] = {-1}; //create memo table and initialise to -1
long long int fibo(long long int n)
{
if(memo[n]>-1) //changing this to if(memo[n]>0) works fine
return memo[n]; //but as such this gives 0 from all my inputs
if(n<=2)
return 1;
memo[n] = fibo(n-1) + fibo(n-2); //recurse
return memo[n];
}
int main()
{
long long int n;
cin>>n;
cout<<fibo(n)<<endl; //calls the fibo function
for(int i=0;i<20;i++) //this prints my memo table used...
cout<<memo[i]<<" ";
}
I am calculating the nth Fibonacci number using top-down dp but my memo table is zeroed out. Even at locations which I am not touching, why?
When you have
long long int memo[20] = {-1};
You are not telling the compiler to initialize the array with all -1. What you are telling it is here is a initializer list and initialize the elements in the array with its contents. Since the list is smaller than the array every missing initializer causes the compiler to zero initialize the corresponding elements.
Because that's how array initialization works in C++. You set the first element of the array memo to -1, and the compiler will value-initialize (before the C++11 standard) or default-initialize (since C++11 and onward) all of of the other elements.
Please read more about aggregate initialization here.
long long int memo[20] = {-1}; actually sets -1 to the first element only. Thereafter they take the value 0.
In your case, given that the Fibonacci series doesn't contain a zero term, I'd use 0, rather than -1 as the indicator, and write
long long memo[20] = {}; /*new C++ standards allow this, note that C doesn't*/
instead.
You are just setting the first element with -1 by doing {-1}.
Here is the excerpt from C++ Programming Language Stroustrup book about Array Initializer:
If the initializer supplies too few elements for an array, 0 is used for the rest. For example:
int v5[8] = { 1, 2, 3, 4 };
is equivalent to
int v5[] = { 1, 2, 3, 4 , 0, 0, 0, 0 };
So your case long long int memo[20] = {-1}; comes under supplying too few elements for the array.
Because the line
long long int memo[20] = {-1};
states that only the first element of memo is initialized as zero.
When you type "memo" only, it refers to a pointer which holds the address of the first element of the array in C++. only when specified by square parentheses -for example memo[3]-, or when explicitly said something like "memo+3" it will point to the indices of the array.
What you would like yo do is to state all indices and initialize them with -1 value.
long long int memo[20] = {[0 ... 20] = -1};

How do sizeof(arr) / sizeof(arr[0]) work?

When looking for a size of an array in a for loop I've seen people write
int arr[10];
for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){}
How is sizeof(arr) / sizeof(arr[0]) the length of the array? How does it technically work?
If you have an array then sizeof(array) returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element (sizeof(array[0])). This gives you number of elements in the array.
Example:
std::uint32_t array[10];
auto sizeOfInt = sizeof(std::uint32_t); // 4
auto numOfBytes = sizeof(array); // 10*sizeOfInt = 40
auto sizeOfElement = sizeof(array[0]); // sizeOfInt = 4
auto numOfElements = sizeof(array) / sizeof(array[0]); // numOfBytes / sizeOfElement = 40 / 4 = 10
LIVE EXAMPLE
Note that if you pass an array to a function, the above won't work since the array decays to a pointer and sizeof(array) returns the size of the pointer.
std::size_t function(std::uint32_t a[]) // same for void function(std::uint32_t a[10])
{
return sizeof(a); // sizeof(std::uint32_t*)!
}
std::uint32_t array[10];
auto sizeOfArray = function(array); // array decays to a pointer inside function()
LIVE EXAMPLE #2
As it is described in the C++ Standard (5.3.3 Sizeof)
1 The sizeof operator yields the number of bytes in the object
representation of its operand. The operand is either an expression,
which is an unevaluated operand (Clause 5), or a parenthesized
type-id.
In this expression
sizeof(arr) / sizeof(arr[0])
there are used two subexpressions with the sizeof operator.
This subexpression
sizeof(arr)
yields the number of bytes occupied by array arr (I suppose that arr is an array).
For example if you declared an array like
int arr[10];
then the compiler has to reserve memory that to hold 10 elements of type int. If for example sizeof( int ) is equal to 4 then the compiler will reserve 10 * 4 = 40 bytes of memory.
Subexpression
sizeof(arr[0])
gives the number of bytes occupied by one element in the array. You could use any index as for example
sizeof(arr[1000])
because the expression is unevaluated. It is only important the size in bytes of the object (an element of the array) used inside the operator.
Thus if you know the total bytes that were reserved for an array
sizeof(arr)
and know how many bytes each element of the array occupies (all elements of an array have the same size) then you can calculate the number of elements in the array by using the formula
sizeof(arr) / sizeof(arr[0])
Here is a simple relation. If you have an array of N elements of type T
T arr[N];
and you know the size of the memory occupied by the array then you can calculate the size of its element by using formula
sizeof( arr ) / N == size of an element of the array.
And vice verse
If you know the size of the memory occupied by the array and the size of its element you can calculate the number of elements in the array
sizeof( arr ) / sizeof( a[0] ) == N - number of elements in the array
The last expression you can rewrite also the following way
sizeof( arr ) / sizeof( T ) == N - number of elements in the array
because the elements of the array have type T and each element of the array occupies exactly the number of bytes that are required to allocate an object of type T.
Take into acccount that usually beginners make such an error. They pass an array as an argument to a function. For example let's assume that you have a function
void f( int a[] )
{
// ...
}
And you pass to the function your array
int arr[10];
f(arr);
then the function uses the pointer to the first element of the array. In fact the function has declaration
void f( int *a )
{
// ...
}
So if you write for example within the function
void f( int *a )
{
size_t n = sizeof( a ) / sizeof( a[0] );
// ...
}
then as a within the function is a pointer (it is not an array) then you will get something like
void f( int *a )
{
size_t n = sizeof( int * ) / sizeof( int );
// ...
}
Usually the size of a pointer equal to either 8 or 4 bytes depending of the used environment. And you won't get the number of elements. You will get some weird value.
int - is equal to 4 bytes
sizeof(int) it means: 1 * 4 = 4
int arr[10] - is holding 10 int
sizeof(arr) it means: 10 * 4 = 40, we got 10 int and every int got 4 bytes,, arr without the [] it means all the arr.
sizeof(arr[0]) it means: 1 * 4 = 4
sizeof(arr) / sizeof(arr[0]) = 10*4 / 1*4 = 10,, and it is the length of the array.
It only works if arr has not been decayed into a pointer, that is, it is an array type, not a pointer type.
sizeof(arr) is the total size occupied by the array.
sizeof(arr[0]) is the size of the first element in the array. (Note that zero length arrays are not permitted in C++ so this element always exists if the array itself exists).
Since all the elements will be of the same size, the number of elements is sizeof(arr) / sizeof(arr[0]).
When dealing with an array (some_type name[some_size]) sizeof(name) is how many bytes the array occupies. Dividing the total size of the array by the size of one element (sizeof(name[0])) gives you how many elements are in the array.
c++ way to use extent, which allows u to get a number of elements in Nth dimension of the array.
see http://en.cppreference.com/w/cpp/types/extent for details
int values[] = { 1 };
std::extent<decltype(values)>::value == 1
Let's take an example like the arr[]={1,2,4,3,5}.
Then the size of the array will be 5 and the size of arr[0] will be "1" BECAUSE it consists of an element in it. Basically it's a subarray the from the above problem it will be 5/1 it will automatically returns the size of array =5.
The difference is
int arr[5] = {1,2,3,4,5};
here arr is Pointer to array and &arr[0] is pointer of type Integer

Strange behavior of C++ array size

I am writing a c++ function to calculate the size of an C-type array in C++
I noticed a very strange behavior when using these two different codes:
code 1:
int sz = sizeof array / sizeof *array;
code 2:
int array_size(const int *pointer)
{ int count=0;
if(pointer)
while(*pointer) {
count++;
pointer++;
}
return count;
}
When I applied these two method on a array, it gave me very strange behavior:
example 1 :
int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6
the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by *pointer, it will give me the correct array elements:
31 24 65 32 14 5
example 2
int array[] = {31,24,65,32,14,5}; // no declared size but init with 6
Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by *pointer in code 2, it gives me :
31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767
which is really not right, so what could be the problem that cause this behavior? and what are those numbers?
Thanks for your answer
This array has 10 elements, regardless of how you initialize it:
int array[10] = {31,24,65,32,14,5};
But the initialization sets the first 6 elements to certain values, and the rest to 0. It is equivalent to this:
int array[10] = {31,24,65,32,14,5,0,0,0,0};
The first calculation using sizeof uses the actual size fo the array (its length times the size of an int), while the second one counts elements until it finds a 0. So it doesn't calculate the length of the array, but the length of the first non-zero sequence in the array.
Note that the second method only "works" if the array has an element with value 0. Otherwise you go out of bounds and invoke undefined behaviour.
array_size assumes that there is a 0 just past the end of the array. That assumption is unjustified.
code 2 is not right. you can't assume an array end with 0

C++ arrays - limit and size

How do you declare an array for a matrix that contains say 4 numbers (2x2)? I assume that int m[4] only allows numbers up to 4. Or does it mean any four numbers? I don't understand the difference.
In a declaration
type array_name[ array_size];
type is the data type that this array stores. The particular value of array under index i, i.e. array_name[i] can be any of the values that type can represent.
In your example int m[4]; declares an array of four integers. The particular value of any of these integers can be any of the values that integer can represent. To know these limits you can print them:
#include <limits>
int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max(); // maximum value
The use of STD should simplify your life in the construction of a matrix :
std::vector<std::vector<int>> M(2, std::vector<int>(2));
But if you want to use arrays :
int x[2][2];
int m [4] would declare an array with 4 uninitialized values of type integer. Remember that these values are zero-indexed,
meaning that to call a value in the array you would call m[0-3]. You may assign any values you like to the array by the following command: m[4] = {Value1, Value2, Value3, Value4} If you prefer, you may also create a loop that will assign values to an array, which can be immensely useful at times.
Keep in mind that arrays are not commonly used in C++, std::vector is far more used, and for good reason.
http://www.cplusplus.com/reference/vector/vector/
int m[4] declares an array of 4 integers. The indexes of the integers will be 0, 1, 2, 3, while the values at those indexes can be any integers. so m[2] = 2003; sets the 3rd value in the array to 2003. As for the 2x2 aspect, you probably want to do something like int m[2][2]; . I think about this as declaring an array of size 2, containing arrays at each spot, instead of ints or floats or whatever. The arrays contained at each spot (there are only two spots so only two arrays in this case) each hold two ints. So if the first value in your matrix is 32, you could set that by doing m[0][0] = 32; or more generally, m[x][y] = value_of_(x,y);
The quickest way to do what you described is probably this, if you know the values ahead of time:
int row0col0 = value at 0th row 0th column;
int row0col1 = value at 0th row 1st column;
int row1col0 = value at 1st row 0th column;
int row1col1 = value at 1st row 1st column;
int m[2][2] = { {row0col0, row0col1}, {row1col0, row1col1} };
or equivalently:
int m[2][2] = {row0col0, row0col1, row1col0, row1col1};
This is referred to as row-major order: elements in a 2d array are sorted first by row, then by column.