C/C++ the result of the uninitialized array - c++

It might be a boring question! thanks!
Here's the code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int a[5] = {0};
int b[5];
cout << a << endl;
cout << b << endl;
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++)
{
cout << b[i] << " ";
}
cout << endl;
return 0;
}
in Ubuntu: g++ a.cpp
In windows with DEV C++ ,MinGW GCC 4.7.2:
So the question is focused on the array b:
I know I haven't initialized the array b.
Array b is full of garbage values, but why there is always having '0' with the fixed position like "X 0 X 0 X"??
What happens inside??
Just a protection mechanism?

That is undefined behavior. There is no guarantee, if these zeros are there, that just accidentally is true.
The explanation is, that for some random reason at these places in memory a 0 was stored before it was reused for your purpose here. Since you allocate your arrays on the stack, these zeroes are probably from a prior function call and might be some padding. The compiler will do that as he pleases.

The behaviour on reading uninitialised elements of an array is undefined. The compiler is allowed to do anything.
(All the elements of a can be read due to the brace initialisation, although in C++ you can write int a[5] = {};).

Related

Result even after crossing the limit of the initialized array in C++

After initialization of an array up to certain limit and then printing the array out of that limit it is still printing the result.Why ?
Example :
#include <iostream>
using namespace std;
int main() {
int A[2] = {};
cout << A[0] << "\n";
cout << A[1] << "\n";
cout << A[2] << "\n";
cout << A[3] << "\n";
cout << A[4] << "\n";
return 0;
}
The Output is:
0
0
0
0
-13120
Here I have just initialized the array till 2 places. But still I am getting the result of A[2],A[3] and so on.
Crossing the limit results in undefined behavior (UB). It can print and looks like working normally, it could crash, it could stuck,or it could be anything.
So, you should not rely on it if it works sometimes.
Exceeding an array's bounds is undefined behaviour. This means that the program may do simply nothing, may print something, may exit the program, may ... behaviour is simply not defined.
So printing out something is still one possible behaviour, but you must not rely on this behaviour.

Is it a similar function in C++11 as in C11 for the twodimensional matrix?

I have noticed that in gcc C11 you can pass any matrix to a function fn(int row, int col, int array[row][col]). How to translate my below placed (in a link to an another stackoverflow answer) program in C11 to a program in C++11?
C - allocating a matrix in a function
As you can see I can pass to functions static and dynamic allocated arrays in C11. Is it possible in C++11?
I have made an exemplary program based on different stackoverflow answers, but all functions work for array1 and none of them works for array2, where double array1[ROW][COL] = { { } } and auto array2 = new double[ROW][COL]() ?
How to make a function for both arrays as is made in C11 fn(int row, int col, int array[row][col])?
#include <iostream>
#include <utility>
#include <type_traits>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
const int ROW=2;
const int COL=2;
template <size_t row, size_t col>
void process_2d_array_template(double (&array)[row][col])
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < col; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
void process_2d_array_pointer(double (*array)[ROW][COL])
{
cout << __func__ << endl;
for (size_t i = 0; i < ROW; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < COL; ++j)
cout << (*array)[i][j] << '\t';
cout << endl;
}
}
// int array[][10] is just fancy notation for the same thing
void process_2d_array(double (*array)[COL], size_t row)
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < COL; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
// int *array[10] is just fancy notation for the same thing
void process_pointer_2_pointer(double **array, size_t row, size_t col)
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < col; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
int main()
{
double array1[ROW][COL] = { { } };
process_2d_array_template(array1);
process_2d_array_pointer(&array1); // <-- notice the unusual usage of addressof (&) operator on an array
process_2d_array(array1, ROW);
// works since a's first dimension decays into a pointer thereby becoming int (*)[COL]
double *b[ROW]; // surrogate
for (size_t i = 0; i < ROW; ++i)
{
b[i] = array1[i];
}
process_pointer_2_pointer(b, ROW, COL);
// allocate (with initialization by parentheses () )
auto array2 = new double[ROW][COL]();
// pollute the memory
array2[0][0] = 2;
array2[1][0] = 3;
array2[0][1] = 4;
array2[1][1] = 5;
// show the memory is initialized
for(int r = 0; r < ROW; r++)
{
for(int c = 0; c < COL; c++)
cout << array2[r][c] << " ";
cout << endl;
}
//process_2d_array_pointer(array2);
//process_pointer_2_pointer(array2,2,2);
int info;
cout << abi::__cxa_demangle(typeid(array1).name(),0,0,&info) << endl;
cout << abi::__cxa_demangle(typeid(array2).name(),0,0,&info) << endl;
return 0;
}
The feature that you are using in C11 was introduced in C99, and was specifically designed to allow efficient and easy handling of multidimensional arrays.
While C++ shares the basic syntax with C when it comes to (multidimensional) arrays, array types are significantly less powerfull in C++: In C++ the sizes of array types are required to be compile time constants. Here are a few examples:
void foo(int a, int b) {
int foo[2][3]; //legal C++, 2 and 3 are constant
int bar[a][3]; //Not C++, proposed for C++17: first dimension of an array may be variable
int baz[a][b]; //Not C++, legal in C99
int (*fooPtr)[2][3]; //legal C++
int (*barPtr)[a][3]; //Not C++, legal in C99
int (*bazPtr)[a][b]; //Not C++, legal in C99
typedef int (*fooType)[2][3]; //legal C++
typedef int (*barType)[a][3]; //Not C++, legal in C99
typedef int (*bazType)[a][b]; //Not C++, legal in C99
int (*dynamicFoo)[3] = new int[2][3]; //legal C++
int (*dynamicBar)[3] = new int[a][3]; //legal C++
int (*dynamicBar)[b] = new int[a][b]; //Not C++
}
As you see, almost everything that's possible in C with dynamic sized arrays is not possible in C++. Even the VLA extension that's proposed for the next C++ standard does not help much: it's restricted to the first dimension of an array.
In C++, you have to use std::vector<> to achieve what you can achieve with C99 variable length arrays. With all the consequences:
The data in an std::vector<std::vector<> > is not consecutive in memory. Your caches might not like this.
There is no guarantee with an std::vector<std::vector<> > that all line arrays have the same length. This can be useful, or a pain, depending on your use case.
If you have an iterator to an element in an std::vector<std::vector<> >, you can't advance it to the corresponding element in the next line.
C++ does not have VLA. It is proposed for C++17 but there's a lot of work to do yet because it is quite a big change to the type system, and using C-style arrays is discourated in C++ anyway.
As you have found, you can use templates when the size is known at compile-time. If the size is not known at compile-time then your best bet is to use a single-dimensional vector wrapped up in a class for accessing it in the way you want to access it.
The vector of vectors is also possible of course; that describes a jagged array. Whether you prefer that over the single large memory block depends on various things (complexity of coding, runtime speed / memory usage considerations etc).

UPDATED: Returning a pointer to an array from a function

I know this is a similar question to previous questions but I couldn't find a suitable answer that I could follow.
I am trying to create an array of values in a function and then return a pointer to this array to be used in later functions and in the main. I am having issues simply in understanding how to properly send and access the array. Following is a portion of my code (I have deleted irrelevant parts only)
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
double *PMS() {
static double w[128];
double dw = 0.05;
int i;
for (i = 1; i <= M; i++) {
w[i] = dw + (2*i - 1) * (dw/2.0);
cout << w[i] << endl;
}
cout << w[i] << endl;
return w;
}
//======================================================================
void RandSea() {
double *omega;
int i;
omega = PMS();
for (i = 0; i <=129;i++)
cout << *omega << endl;
}
int main() {
data(values);
Pierson_Moskowitz();
RandSeaState();
}
The array is not correctly sending the values 0x6021e0 from cout<<omega<<endl; in the RandSea function.
the value for omega is just zero.
There are many things to note here:-
1) array indices start at 0 and ends at size-1.
2) cout << omega << endl;
This would be printing the base address of the array.
You should use :-
omega = PMS();
for ( int i = 0; i < 129; i++ ) <<<<Here 129 should be the number of elements array has
{
cout << *(omega + i) << endl;
}
3) You are returning the address of array to the caller. How would it get to know how many elements are there in an array.
"My second question is that I'm also having some trouble understanding the difference between the * and the & for pointers"
The & is known as "address of" operator. It used to get an address of an object. And '*' is "value at address of" operator in context of pointers.

A c++ program that stores the positions of each bit 1 in a binary sequence

I have made this code to store the position of each bit 1 entered in a binary sequence. The output of the program is not what it is desired. The output I get for 10100 is 0x7fff9109be00. Here is the code:
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset <5> inpSeq;
int x = 0;
int xorArray[x];
unsigned int i;
cout << "Enter a 5-bit sequence: \n";
cin >> inpSeq;
for ( i = 0; i < inpSeq.size(); i++)
{
if ( inpSeq[i] == 1 )
{
x = x+1;
xorArray[x] = i;
}
}
cout << xorArray << "\n";
}
Update for clarity: What I had in mind was that 'cout << xorArray' will print bit 1's positions.
cout << xorArray << "\n";
This does not print the elements of xorArray; it prints its address.
You must iterate ("loop over") it:
for (auto x : xorArray)
cout << x << ' ';
cout << '\n';
Your other problem is that you're trying to use a variable-length array, which does not exist in C++. Use a vector instead.
Now it gives you your desired output:
#include <iostream>
#include <bitset>
#include <vector>
using namespace std;
int main()
{
bitset<5> inpSeq("10111");
std::vector<int> xorArray;
for (unsigned int i = 0; i < inpSeq.size(); i++) {
if (inpSeq[i] == 1)
xorArray.push_back(i);
}
for (auto x : xorArray)
cout << x << ' ';
cout << '\n';
}
If you're not using C++11 for whatever reason, you can perform that final loop the traditional way:
for (std::vector<int>::const_iterator it = xorArray.begin(),
end = xorArray.end(),
it != end; ++it) {
cout << *it << ' ';
}
Or the naive way:
for (unsigned int i = 0; i < xorArray.size(); i++)
cout << xorArray[i] << ' ';
I am a little unclear on exactly what you are trying to achieve, but I think the following might help.
#include <iostream>
#include <bitset>
#include <list>
using namespace std;
int main() {
bitset<5> inpSeq;
unsigned int i;
list<int> xorList;
cout << "Enter a 5-bit sequence: \n";
cin >> inpSeq;
for (i = 0; i < inpSeq.size(); ++i) {
if (inpSeq[i] == 1) {
xorList.push_back(i);
}
}
for (list<int>::iterator list_iter = xorList.begin();
list_iter != xorList.end(); list_iter++)
{
cout << *list_iter << endl;
}
return 0;
}
The reason why I am using a list is because you mentioned wanting to store the positions of the 1 bit. The list is being used as the container for those positions, in case you need them in another point in the program.
One of the problems with the original code was that you assigned variable 'x' the value 0. When you declared xorArray[x], that meant you were essentially creating an array of length 0. This is incorrect syntax. It looks like you actually were trying to dynamically allocate the size of the array at runtime. That requires a different syntax and usage of pointers. The list allows you to grow the data structure for each 1 bit that you encounter.
Also, you cannot print an array's values by using
cout << xorArray << endl
That will print the memory address of the first element in the array, so, xorArray[0]. Whenever you want to print the values of a data structure such as a list or array, you need to iterate across the structure and print the values one by one. That is the purpose of the second for() loop in the above code.
Lastly, the values stored are in accordance with the 0 index. If you want positions that start with 1, you'll have to use
xorList.push_back(i+1);
Hope this helps!

Array of int or vector?

i'm trying to store some elements that is going to change every time, but i don't know which
way is better and why. I'm thinking about two ways, 1) declaring array of int and loop or
use vector's.
Which way is better and why?
Does declaring array of int have any future memore problems as leak?
the code down below show the two ways i'm talking about:
1)
#include <iostream>
#include <vector>
int main()
{
int x[5];
x[0] = 10;
x[1] = 20;
x[2] = 30;
x[3] = 40;
x[4] = 50;
for(unsigned int i = 0;i<=sizeof(x[5]); i++)
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
system("pause");
return 0;
}
2)
#include <iostream>
#include <vector>
int main()
{
std::vector<int> x;
x.push_back(10);
x.push_back(20);
x.push_back(30);
x.push_back(40);
x.push_back(50);
for(unsigned int i = 0;i<=x.size()-1; i++)
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
system("pause");
return 0;
}
If this is all you have to do, and your array will always have a size that is known at compile time, then you do not need std::vector.
On the other hand, in C++11 you could use std::array instead of a plain C array (std::array is a zero-overhead, safer and more functional wrapper over a C array):
#include <iostream>
#include <array>
int main()
{
std::array<int, 5> x = { 10, 20, 30, 40, 50 };
for (unsigned int i = 0; i < x.size(); i++)
// ^^^^^^^^
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
}
Here is a live example. Notice, that std::array offers a size() member function which you may want to use instead of the sizeof operator.
Moreover, since std::array is a standard sequence container, you could iterate through its element this way:
std::size_t i = 0;
for (auto e : x)
{
std:: cout << "x[" << i++ << "] = "<< e << std::endl;
}
Here is a live example.
If the size is known at compile time, use std::array. If not, use std::vector. In either case, use iterators to look at the elements:
typedef std::array<int> my_container_type;
typedef my_container::iterator iterator;
my_container_type my_container = { whatever };
for (iterator it = my_container.begin(); it != my_container.end(); ++it)
std::cout << "x[" << (it - my_container.begin()) << "] = " << *it << '\n';
By using iterators you greatly reduce the risk of accidentally using a loop limit like sizeof(x[5]), which is nonsense.
Neither is "better". They both address entirely different use cases.
If you know the array size at compile time and are 100% sure it will never change, sure, use a plain old array. It has less overhead, and the compiler can even aid you with static analysis by spotting any attempts to read outside the boundaries.
On the other hand, if you are unsure of the array's side (i.e. you will be reading input from a file or the user), then use the std::vector. It can grow to any size to meet your needs.