C++ array gives me garbage value [duplicate] - c++

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 7 years ago.
I just started learning c++ and came to Arrays. So what I want to do is perform some function on the array that was passed in function. So for this I tried small example
#include <iostream>
using namespace std;
void printArray(int data[]){
cout<<"len is :"<< sizeof(data)<<endl;
for(int i = 0 ;i<sizeof(data); i++){
cout<<data[i]<<" ";
}
cout<<endl;
}
int main() {
int data[] = {1,2,3,4,5,6};
printArray(data);
cout<<"in main :"<<sizeof(data)<<endl;
for(int i = 0 ;i<sizeof(data); i++){
cout<<data[i]<<" ";
}
return 0;
}
And Following is the output I obtained from the code
len is :8
1 2 3 4 5 6 738192384 -1126994503
in main :24
1 2 3 4 5 6 738192384 -1126994503 0 0 -1061892411 32677 0 0 -1665163256 32766 0 1 4196851 0 0 0 463403231 1946389667
I am not understanding where the process goes wrong. or is some thing in my code that make these weird changes to happen. and also the sizeof() is giving two values for the same array.Correct me where I am wrong anywhere.
I am using Eclipse software with c++ plugin added.
Thanks in advance for help!!

sizeof doesn't work if you pass an array to the function in this fashion. Try passing the size with the array or pass the begin and end pointers of the array.
If you don't mind templates, you can pass the array by reference:
template<unsigned length>
void printArray(int (&data)[length]) {
//length is the length of data
}

Related

Segmentation fault:Why the array index here goes out of bounds?

I was trying to solve the problem here- https://www.codechef.com/APRIL19B/problems/FENCE and initialized the array to 0 but when I try to access the value at arr[0][4] with n=4 and m=4, it prints a garbage value.
I tried to initialize using vector thinking I'm making some mistake in the initialization of array, it works for the sample testcase but still gives segmentation fault.
Here is my code -
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
long long n,m,k,res=0;
cin>>n>>m>>k;
//vector<vector<long long>> arr(n+2,vector<long long>(m+2,0));
long long arr[n+2][m+2]={0};
long long vec[k][k];
for(unsigned int it=0;it<k;it++){
int t1,t2;
cin>>t1>>t2;
arr[t1][t2]=1;
vec[it][0]=t1;
vec[it][1]=t2;
}
cout<<"values:"<<arr[1][4]<<endl;
for(unsigned int itr =0;itr<k;itr++){
int j = vec[itr][0];
int i = vec[itr][1];
//cout<<i<<" "<<j<<endl;
res+=4-(arr[i-1][j]+arr[i+1][j]+arr[i][j-1]+arr[i][j+1]);
}
cout<<res<<endl;
}
return 0;
}
Edit:
The sample input is:
Example Input
2
4 4 9
1 4
2 1
2 2
2 3
3 1
3 3
4 1
4 2
4 3
4 4 1
1 1
Example Output
20
4
The constraints:
1≤T≤10
1≤N,M≤10^9
1≤K≤10^5
1≤r≤N
1≤c≤M
the cells containing plants are pairwise distinct
I expect the output to be- 20 for the first testcase but get garbage value.
When declaring an array in C++, its size must be a constant expression - that is, the size must be known at compile time. Your compiler ought to be complaining about these lines because m, n, and k are uninitialized (more correctly, initialized to indeterminate values) at compile time:
long long arr[n+2][m+2]={0};
long long vec[k][k];
I think that array is getting out of bounds in arr[i-1][j] or arr[i+1][j] or arr[i][j+1] or arr[i][j-1] that why the error is coming.

Balloon Sort C++

I am researching about the Balloon Sort because it was one of my assignments, but the Google give me one Balloon Sort link sample only and the rest was Bubble Sort.
I compiled the code in Dev C++ and said that it has some error...
Here's [a link] (http://www.codemiles.com/c-examples/balloon-sort-algorithm-c-implementation-code-sorting-array-t10823.html) ! That Google gave me...
here is the code...
#include<iostream>
using namespace std;
void balloon()
{ int num, N[10], x, y, z,temp;
clrscr();
cout<<"How many number would you like to sort? ";
cin>>num;
cout<<"Input the "<<num<<" numbers:"<<endl;
for(x=0;x<num;x++)
cin>>N[x];
for(x=0;x<num;x++)
{
for(y=0;y<num-x;y++)
{ if(N[x] > N[x+y])
{ temp=N[x];
N[x] =N[x+y];
N[x+y]=temp;
}
}
cout<<"pass "<<x+1<<"] ";
for(z=0;z<num;z++)
{
cout<<setw(5)<<N[z];
}
cout<<endl;
}
}
Error Picture Link
Can you help me how to code the Balloon Sort in C++ with some explanations... Thanks in advance!
It will have some error because the compiler will search the int main() so change the void balloon, and remove the clrsrc();
Since you used the setw(), you must use the #include <iomanip>
The header is part of the Input/output library of the C++ Standard Library. It defines the manipulator functions resetiosflags(), setiosflags(), setbase(), setfill(), setprecision(), and setw(). These functions may be conveniently used by C++ programs to affect the state of iostream objects.
And lastly you must make the cout<<setw(5)<<N[z]; into cout<<std::setw(5)<<N[z];
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{ int num, N[10], x, y, z,temp;
cout<<"How many number would you like to sort? ";
cin>>num;
cout<<"Input the "<<num<<" numbers:"<<endl;
for(x=0;x<num;x++)
cin>>N[x];
for(x=0;x<num;x++)
{
for(y=0;y<num-x;y++)
{ if(N[x] > N[x+y])
{ temp=N[x];
N[x] =N[x+y];
N[x+y]=temp;
}
}
cout<<"pass "<<x+1<<"] ";
for(z=0;z<num;z++)
{
cout<<std::setw(5)<<N[z];
}
cout<<endl;
}
}
and if you run it... here is my sample output
How many number would you like to sort? 5
Input the 5 numbers:
8
2
4
9
0
pass 1] 0 8 4 9 2
pass 2] 0 2 8 9 4
pass 3] 0 2 4 9 8
pass 4] 0 2 4 8 9
pass 5] 0 2 4 8 9
--------------------------------
Process exited after 8.305 seconds with return value 0
Press any key to continue . . .
Hope this works on your assignment! Good Luck!

Why not causing a segmentation error? [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 6 years ago.
#include <iostream>
using namespace std;
int main(){
int a[3], no;
cout << "Index Value\n";
for(int i = 0; i < 100; i++){
cin >> no;
a[i] = no;
cout << i << "\t" << a[i] << endl;
}
return 0;
}
Here I initialized a[ 3 ]. In for loop, I'm feeding input 100 times to a[ ], exceeding the indices of [ 3 ].
Why don't it give segmentation error right after when i equals 4.
Input
1 2 3 4 5 6 7
Output
Index Value
0 1
1 2
2 3
4 0
5 5
6 6
7 7
Output is wrong when Index equals 4. Printed 0 . Expected 4
Unfortunately for the debugging programmer, C and C++ programs don't usually segfault when you write past the end of an array. Instead it will usually silently write over whatever the pointer arithmetic as up to -- if the OS allows it. This often overwrites other variables or even program code, causing confusing and unpredictable errors.
I have used the word "usually" here because according to the standards this is "undefined behaviour" -- that is, the compiler and runtime can do anything they like.
When developing and testing, it can be very useful to use a library such as electricfence, which puts extra checks into memory operations and would make your program fail in the way you expect.

C++ for loop and do-while loop of a single dimensional array gives questionable output [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am taking a course on edx.org Introduction to C++ by Microsoft. I get unwanted output when looping through a single dimensional array. The code is below.
<#include <iostream>
int main() {
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 1; arrayName[i] <= 20; i++) {
std::cout << i << std::endl;
}
The output of this is:
1
2
3
4
5
6
7
8
9
10
11
Where does the 11 come from? And, if I make i=0, it also prints a 0. How does it print more than 10? And, when I try to change arrayName[10] to arrayName[9], I get a compiler error that there are too many initialized values:
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
do {
std::cout << i << std::endl;
i++;
} while (arrayName[i] < 5);
The output is:
12
13
14
15
16
17
18
That do-while loop outputs 7 integers that I did not specify to be included in the arrayName[] array.
I don't know what I am doing wrong or what I am not understanding.
Please help. Thank you!
First, note that arrays in c++ start at index 0. So in int arrayName[3] = {10, 42, 88}; then arrayName[1] is 42, not 10. That means the last element in this array is int arrayName[2]. There is no element at index 3.
Your array only contains 10 elements (indices 0 to 9). The standard does not specify what happens when you access an element past the end of an array, anything can happen. In your case, arrayName[10] and arrayName[11] happens to give you something less than or equal to 20, and then arrayName[12] gave you something greater than 20, ending the loop. If you try it on another computer, or even at a different time, the results will vary. It might also crash (this is the best case scenario).
See this answer for more information on undefined behavior.
I finally found this: Correct way of loop through the C++ arrays, answer by https://stackoverflow.com/users/1619294/mark-garcia.
Changed my code to:
std::cout << "Looping through arrayName3 with std::array and letting the compiler determine how many objects to print:" << std::endl;
// Need to #include <array>
std::array<int, 10> arrayName3 = { 1,2,3,4,5,6,7,8,9,10 };
for (const auto& i : arrayName3) // Range-for
{
std::cout << i << std::endl;
}
The output was what I wanted:
1
2
3
4
5
6
7
8
9
10
This let's the compiler know it is deciding what to output. It would be great to know how to change this to control how many indices to loop through.

Replacing each number within an array with the maximum number up to that point

#include<iostream.h>
#include<fstream.h>
ifstream f("date.in");
using namespace std;
int i;
int P(int a[100],int k,int max)
{
max=a[1];
for(i=2;i<=k;i++)
if(a[i]>max)
max=a[i];
return max;
}
int main()
{
int x,a[100],n;
f>>n;
for(i=1;i<=n;i++)
f>>a[i];
for(i=2;i<=n;i++)
a[i]=P(a,i,x);
for(i=1;i<=n;i++)
cout<<a[i]<<" ";
}
My "date.in" file consists of the following :
12
4 6 3 7 8 1 6 2 7 9 10 8
As the title states, the program should modify the array from within the file such that each number has the maximum value found in the array up to, and including, the position of that respective number. I've gone through it a hundred times but cannot figure out what's wrong with my code.
When compiled, I get the following:
4 6 3 7 8 8 6 8 7 9 10 10
Any assistance would be appreciated.
int i;
Globals are usually a bad idea. Because this loop:
for(i=2;i<=n;i++)
a[i]=P(a,i,x);
and this loop:
for(i=2;i<=k;i++)
if(a[i]>max)
max=a[i];
are running "at the same time", and thus i in the first one is NOT counting from 2 to n properly, it's only actually getting the first index and then the even indexes. (Check your results, the even indexes are 100% correct: x 6 x 7 x 8 x 8 x 9 x 10). If you use counters local to each loop: for(int i=2; ... then this problem wouldn't be happening.
Also your entire design is slow. Not sure why you did it that way, because it can be done easily in a single pass: http://ideone.com/LmD0HX.
And use <iostream> not <iostream.h>. They're actually different files.