C++ What exactly happened here? [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 1 year ago.
Improve this question
While doing a program, I came up with an unintended behaviour in dynamic arrays. After I did a few tests, I ended up with this code.
#include <iostream>
unsigned long index;
template<typename T>
class A
{
public:
void Set()
{
T* target = new T[index];
for (unsigned int i = 0; i < index; i++)
{
target[i] = i;
}
this->value_ = target;
index++;
}
T* value_;
};
int main()
{
A<int> test;
test.Set();
std::cout << test.value_[0] << '\n';
test.Set();
std::cout << test.value_[1];
}
Returning the following values:
11104472
11075776
The values change each time I execute the program, however, I thought the output would be "0" and "1". I suppose they are memory addresses, but why is the program returning them and not the expected output?

Just look which values index will have. It is initialized with 0. So in the first test.Set(); you create an 0 length array. To even read it later is wrong and leads to so called undefined behavior. In the second call of set, index will have a value of 1, so you create an array of length 1 and initialize that first element on position 0 correctly with 0, but you then try to print out test.value_[1] which is not the first element but the second. Remember array indices start with 0. So this is also an out of bounds read i.e. a wrong doing punishable by random behavior.

Related

Initializing an array belonging to a class [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 months ago.
Improve this question
CODE1(input):
#include <cstdio>
struct College {
char name[256];
};
void print_name(College* college_ptr) {
printf("%s College\n", college_ptr->name);
}
int main() {
College best_colleges[] = { "Magdalen", "Nuffield", "Kellogg" };
print_name(best_colleges);
}
OUTPUT:
Magdalen College
I have read that "At the slightest provocation, an array will decay into a pointer.A decayed
array loses length information and converts to a pointer to the array’s first element."
For example:
int key_to_the_universe[]{ 3, 6, 9 };
int* key_ptr = key_to_the_universe; // Points to 3
QUESTION1 :
I have also learned how a class and array are initialized but i dont understand how an array in a class can be initialized. According to me array in a class should be initialized ( referring CODE1) this way :
College best_colleges;
best_colleges.name[]={"Magdalen", "Nuffield", "Kellogg"};
QUESTION2:
(Referring CODE1)I also dont understand that if best_colleges array gets converted to pointer college_ptr which points to first element of it i.e
College* college_ptr = &best_colleges[0];
then in function "print_name" , "college_ptr->name" should be equal to "&best_colleges[0]->name". why we need to write "college_ptr-> name" ?
QUESTION 3:
I dont understand if best_colleges is a class or an array according to how it has been initialized.

Pointer in c++for scanning an array [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
How to scan an array in c++ using pointer?
I have learned c programming .so i tried that way.
include<iostream>
using namespace std;
main()
{
int a[5],*p,i;
p=&a[5];
for(i=0;i<5;i++)
{
cout<<"enter"<<i+1<<endl;
cin>>(p+i);
}
for(i=0;i<5;i++)
{
cout<<*(p+i)<<endl;
}
}
I am expecting to scan using pointer just like in c programming
p=&a[5];
&a[5] is the address to one past the last element of the array. Incrementing this pointer, as well as indirecting through the pointer have undefined behaviour.
What you need is a pointer to the first element. You can use:
p = &a[0]; // this
p = a; // or this
Or you could simply not use p in the first place, and access a[i] directly.
cin>>(p+i);
This is wrong. p+i is a pointer. You cannot extract into an int pointer. You should extract into the integer object instead:
cin >> p[i];
cin >> a[i]; // or without p, as I pointed out above

Elements in an array will not change 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 4 years ago.
Improve this question
void Remove(int x)//x is the number that i want to remove
{
for(int i=0;i<CAPACITY;i++)//loop is to find the first case of x
{
if(x==data[i])//if x is in data
{
cout<<data[i]<<endl;//for debugging
data[i]==0; //change x to 0
cout<<data[i]<<endl;
}
}
}
when i cout to see if it works the number that i wanted to delete is still there.
Here is the output before i run it when x=15:
12,15,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
I used cout to see if there was a problem with the condition however it runs if x is in the array.
Here is the output after, even if x is in the array:
12,15,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
In your If loop you use comparison operator '==' so put only one = which means you assign variable x to data array.
The problem in in the line data[i]==0; //change x to 0
== is an comparison operator. In order to assign a value use = instead. So:
data[i] = 0

Array not printing Properly 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 5 years ago.
Improve this question
When running this program, if the value of n is set to 10 it will print the indices of array a and stored values from a[0] to a[9]. However if I set the value of n to more than 10 the then it only prints the indices of array a from a[0] to a[5] with their stored values. Can someone explain to me why this is happening?
#include <iostream>
using namespace std;
int main()
{
int a[10];
int i, n=11;
for(i=0; i<n; i++) {
a[i]= 5;
}
cout<<"The array is: \n";
for(i=0; i<n; i++)
{
cout<<"a["<<i<<"] = "<<a[i]<<endl;
}
return 0;
}
If you increase the value of n past the size of the array (or equal to it indexing from 0), you are going past the end of the array. And going past the end of the array is undefined behavior. If your program is exhibiting undefined behavior. Anything can happen. See this blog post from Microsoft for more on undefined behavior
If you switch to an std::array instead of a C array and use .at(), then something well defined will happen, you will get an std::out_of_range exception. For more see http://en.cppreference.com/w/cpp/container/array/at and http://en.cppreference.com/w/cpp/container/array

Run-Time Check Failure #3 - The variable 'result' is being used without being initialized [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
Having issues with my code... the program compiles, but then it gives the following statement "Run-Time Check Failure #3 - The variable 'result' is being used without being initialized." It then ends the program at that point. Everything I have after trying to run the function is ignored. What should I do?
double result;
for (int i=0; i<nRows; i++)
{
absum.push_back(vector<double>());
for (int j=0; j<nColumns; j++)
{
double temp;
temp = matrixa[i][j]+matrixb[i][j];
absum[i].push_back(temp);
cout << temp << '\t';
}
cout << endl;
}
return result;
At the top of your code you have:
double result;
At the moment it's not initialised to anything at all, so the compiler won't use it. So you need to need to initialise it thus:
double result = 0;
It's also generally good practice to initialise every variable you use in C++, that way you don't get nasty compiler messages, and don't run the risk of returning some random chunk of memory. You always want to start your program from a known state, so if you know that result is 0, then all is good.
C++ is picky about this sometimes, have you tried double result = 0?