How do I initialize and cout an array in C++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I do have a problem with an array I am loading and I cout later on in the code.
The array is initialized as:
int array[51][2]={{1,2},{7,4},/* ... */ }
The dots imply the other 49 missing tuples.
Later on, when I just want to cout the array I use:
for(int k=0;k<nProducts;k++){
for(int t=1;t<=T;t++){
cout << array[k][t];
}
cout << endl;
}
Unfortunately this does not work at all. Visual Studio happily compiles the program, but when I run it (ConsoleApplication) it crashes at this point. When I comment out the "cout-part" it works fine. But I doubt the array is used as it should be in the rest of the code.
Could you help me somehow with that ? I just cannot find my mistake in any literature, which seems to perfectly do the same I do.

Change this:
for(int t=1;t<=T;t++)
To this:
for(int t=0;t<T;t++)
Indexes in C/C++/Java/etc. are between 0 and N-1.

You are accessing indices that are out of bounds - the array is indexed from 0, so the last valid index is N-1. When you try to access the element at index N, you get IndexOutOfRangeException which causes the termination of the program.

Related

Why is 1e-12 + 1 = 1 in C++, but not in C? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In C I put in a big number, like 1e-12, in float data and add 1. It's gave me a correct answer.
In C++ I made the same, but when I add 1 to 1e-12, it returns me 1.
float a = 1e-12;
std::cout << "The number is : " << a + 1 << std::endl;
Output:
The number is: 1
I don't have any error messages. The program just returns the wrong result.
(!! 1e-12 + 1 is not equal to 1!!)
Compilers by default take some short-cuts when doing floating-point math. (They typically have a command-line switch to enforce the rules)
In this case, the rule is that the compiler should store the double value 1e-12 as a float in a, and then, in the output statement, add 1 to the stored value.
The optimization is probably that one of the compilers never stored the value; instead, it added 1 to the double value 1e-12. With the higher precision initial value there are more low bits in the fraction part, and that will affect the result of adding 1.
So the results can be different, depending on how the compiler treats those values.
That's just handwaving, though; if this is really important to you, look at the machine code that the compiler generates in both cases to see what's being done differently.

2D-Array deletes elements itself when new elements get stored [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
edit: I didn't initialise the array with the right size. I should have used 8 instead of 7. I had to learn that Arrays start counting at 0, but when initialising the don't!
I have a 2 dimensional Array storage[x][y] and want to store for each x value 8 different y values. For some reason I can read out a specific place in the array, for example [48][7] and after filling other spaces in the array the [48][7] value has changed even tough I never touched it.
int storage[127][7];
void store(){
storage[48][0] =0b01111110;
storage[48][1] =0b01111110;
storage[48][2] =0b11100011;
storage[48][3] =0b11010011;
storage[48][4] =0b11001011;
storage[48][5] =0b11000111;
storage[48][6] =0b01111110;
storage[48][7] =0b01111110;
Serial.println(storage[48][7], BIN); // returns 01111110
storage[49][0] =0b00000000;
storage[49][1] =0b11000001;
storage[49][2] =0b11000001;
storage[49][3] =0b11111111;
storage[49][4] =0b11111111;
storage[49][5] =0b00000001;
storage[49][6] =0b00000001;
storage[49][7] =0b00000000;
Serial.println(storage[48][7], BIN); // returns 0
}
Depending on the order in which I store the values some of them delete each other.
Why do I suddenly lose data?
You are defining a 2D-array with row-size 7, but you access 8 elements of a single row:
int storage[127][7];
storage[48][0] =0b01111110;
...
storage[48][7] =0b01111110;
Note that 0..7 are actually 8 elements, not 7. So you'd have to define storage as...
int storage[127][8];
One might discuss now if int storage[127][7];storage[48][7] =0b01111110 is undefined behaviour;
Yet the most probably behaviour is that storage[48][7] maps to the same memory address as storage[49][0]. Hence, when you assign storage[49][0] =0b00000000;, then you write to storage[48][7] "as well" and it will become 0b0000000.

std vector memory allocation linux vs windows compilers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
A very simple program testing the STL implementations between Intel compiler on linux (Intel 18.0) and visual c++ on windows (MSVC 2015).
Primarily, how to make linux fatal out/ crash the same way as windows (since i have a huge codebase). Technically i was expecting a signal 11 from linux, not to throw a garbage value everytime for whatever the size of vector i tested.
Can someone explain what is happening under the hood (memory allocation wise and their rules and if it is implementation/platform/compiler dependent).? Just for my understanding.
'
#include "iostream"
#include "vector"
using namespace std;
int main(int argc,char* argv[])
{
vector<int> v;
//v.resize(5); (my bad, please ignore this, i was testing and posted incorrect version)
cout<<"Initial vector size: "<<v.size()<<endl;
for(int i=1;i<=5;++i)
{
v.push_back(i);
}
cout<<"size of vector after: "<<v.size()<<endl;
for(int j=5;j>=0;--j) // Notice my upper bound.
{
cout<< "printing " <<v[j]<<std::endl;
}
return 0;
}
Both had no problems compiling as one can expect. Subsequently, Windows crashed with a nice message "vector subscript out of range" while linux threw some garbage value everytime and continued.
Assuming you put v.resize(5) by mistake, here are some answers:
how to make linux fatal out/ crash the same way as windows (since i have a huge codebase).
Use std::vector::at() that validates index and throws exception by design. std::vector::operator[] not suppose to validate index and even if some platform does it for some configuration (looks like Windows compiler in debug has such validation), you cannot demand it everywhere.
Technically i was expecting a signal 11 from linux, not to throw a garbage value everytime for whatever the size of vector i tested.
It is a problem of your expectation. Giving invalid index to std::vector::operator[] leads to Undefined Behaviour, and you cannot expect that to give signal 11 or something else in particular.
FYR:
std::vector::operator[]
Returns a reference to the element at specified location pos. No bounds checking is performed.
std::vector::at()
If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
emphasis is mine.
As for memory allocation, it is implementation specific, most of them would not allocate memory exactly for 5 elements but more in advance, to make it efficient, so that's why your code on Linux did not crush, but produced garbage, as you read value from uninitialized memory. But that can change any moment and you should not rely on this behavior in any way.

Difference Between initializing an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have been getting a weird output if I initialize an array using a variable instead of a constant
the two code below produces a different output for me.
int x =7;
int arr[x];
and
int arr[7];
the first one generates this output
78 9 73 32 6422216 50 42
and the 2nd one
78 9 73 54 29 50 42
I need to use the size of an vector for the array size.
I have tried making the variable constant but it doesn't makes a difference.
edit
using the array here
int arr[size];
for(int j=i;j<nums.size();j++)
arr[j+1]=nums[j];
arr[i]=nums[signs.size()];
for(int j=0;j<nums.size();j++)
nums[j]=arr[j];
In neither of your two cases is the array initialized.
Without an explicit initializer, the contents of an array (or any variable) are indeterminate. You can't predict what those values will be. And if one of those values happens to be a trap representation, you invoke undefined behavior if you attempt to read that value.
If you want your array to have a particular set of values to start, you need to set those values explicitly, either with an initializer or by assignment.

Why does the copy constructor for std::string appear to be faster than its move counterpart? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to learn move semantics and I read that a move would likely be faster than a copy. However, I see quite the opposite for the following trivial code:
for (int i = 0; i < 100000000; ++i) {
std::string a("Copy");
std::string b = a;
}
for (int i = 0; i < 100000000; ++i) {
std::string a("Move");
std::string b = std::move(a);
}
And here's the time it takes on my mac:
$ time ./copy.out
real 0m2.511s
user 0m2.481s
sys 0m0.011s
$ time ./move.out
real 0m3.993s
user 0m3.933s
sys 0m0.020s
As one of the comments suggests, most library implementations do a "short string optimization", SSO, wherein for a sufficiently short string (some specific length, for a given implementation), the entire string is stored in the body of the string object, on the stack. When your data is stored entirely on the stack, moving is the same as copying. All the implementations I know will SSO a 4 character string, so whether you move or copy it's pretty much well the same operation.
If you output the result of sizeof(sring), choose a string larger than that, and use the same string for both cases. Also make sure optimizations are on.
This approach to micro-benchmarks is not so great. It's generally better to randomize data outside of the timing region, then perform the operation in a loop which is timed. Using the same constant data can often lead to crazy compiler optimizations that invalidate your results.