Why does this variable change in the code? [duplicate] - c++

This question already has answers here:
Can a C/C++ program seg-fault from reading past the end of an array (UNIX)?
(3 answers)
Closed 6 years ago.
I wrote a mergesort function in c++. In which a pass wrong value(array out of bound) of upper limit in function.
int a[]={6,5,2,4,6,78,88,76,33,44,54,212,344,56,677};
int n=sizeof(a)/sizeof(a[0]);
printf("n=%d\n",n);
merges(a,0,n); // if should be 'merges(a,0,n-1)'
printf("n=%d\n",n);
I think in argument only copy of a variable is passed. Original value does not change. but Checking before and after merges() function I got two different values. I can't figure out why?
output:
n=15
n=677
Here is complete code:
#include<bits/stdc++.h>
using namespace std;
void mergeit(int a[],int l,int mid,int r)
{
int n1=mid-l+1;
int n2=r-mid;
int ll[n1+1];ll[n1]=INT_MAX;
for(int h=0;h<n1;h++)ll[h]=a[l+h];
int rr[n2+1];rr[n2]=INT_MAX;
for(int h=0;h<n2;h++)rr[h]=a[mid+1+h];
int i=0,j=0;
for(int k=l;k<=r;k++)
{
if(ll[i]<rr[j])
{
a[k]=ll[i];i++;
}
else{a[k]=rr[j];j++;}
}
}
void merges(int a[],int l,int r)
{
if(l<r)
{
int mid=(l+r)/2;
merges(a,l,mid);
merges(a,mid+1,r);
mergeit(a,l,mid,r);
}
}
int main()
{
int a[]={6,5,2,4,6,78,88,76,33,44,54,212,344,56,677};
int n=sizeof(a)/sizeof(a[0]);
printf("n=%d\n",n);
merges(a,0,n); //array out of bound- it should be 'merges(a,0,n-1)'
printf("n=%d\n",n);
}

It happens because when you write to memory out of bounds, the program's behaviour is undefined. One possible behaviour that may be observed is that n changes in value.
The language does not specify any guarantees about the behaviour of the program. But from the implementation perspective, it is quite possible, that n and a[n] happen to share the same address on the stack.

Related

Passing a typecasted array pointer to a function in C++

#include<bits/stdc++.h>
using namespace std;
void foo(float a[]){
for(int i=0;i<5;i++){
cout<<a[i]<<endl;
}
}
int main()
{
int a[]={1,2,3,4,5};
foo((float*)a);
return 0;
}
I'm trying to pass an int array to a function accepting float array as typecast. But, the results are flabbergasted as I'm getting negative exponential floating number. Please help me with explaining what is happening to the function.

what is the difference in the following c++ codes regarding call by reference [duplicate]

This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 3 years ago.
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int temp=*x;
*x=*y;
*y=temp;
cout<<*x<<endl<<*y<<endl<<"Bro"<<endl;
}
int main()
{
int a=10,b=5;
swap(&a,&b);
cout<<"HI"<<endl;
cout<<a<<endl<<b<<endl;
return 0;
}
and
#include<iostream>
using namespace std;
void swap(int &x, int &y)
{
int temp=x;
x=y;
y=temp;
cout<<x<<endl<<y<<endl<<"Bro"<<endl;
}
int main()
{
int a=10,b=5;
swap(a,b);
cout<<"HI"<<endl;
cout<<a<<endl<<b<<endl;
return 0;
}
Both the codes do give the same output but i don't get the fact that if we are only passing only the variable, how do the addresses get swapped
Both of the codes do the same thing and both of them use call-by-reference for passing the variables to the swap function. but the methods are different. the first code uses pointers for achieving this goal, while the second code uses references. in the signature of the swap function in the second code you can see the & symbol which means the input arguments must be addresses not just values. by calling the swap function, the addresses of arguments will be passed automatically to the swap function rather than their values.
For further reading take a look at the differences between pointers and references.

Is there a differene between int x[] and int *x? [duplicate]

This question already has answers here:
C/C++ int[] vs int* (pointers vs. array notation). What is the difference?
(5 answers)
Closed 8 years ago.
I'm studying a function to search for a number where that goes as the following..
int sequential_search (int num, int a[], int size);
And in main , a is defined as the following.
int *a;
a = new int[size];
So I was wondering if its the same thing..
Thanks in advance
When used as function parameter then there is no difference.
int sequential_search (int num, int a[], int size);
is equivalent to
int sequential_search (int num, int *a, int size);
Otherwise both are different: int x[] declare x as an array of ints while int *x declare x as a pointer to int.

heapsort implementation in c++

i have following code for heapsort
#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
int s=a[i];
a[i]=a[j];
a[j]=s;
}
void sink(int a[],int k,int n){
//int n=sizeof(a)/sizeof(int);
while(2*k<=n){
int j=2*k;
if (j<n && (a[j]<a[j+1])) j++;
if (a[k]>=a[j]) break;
exch(a,k,j);
k=j;
}
}
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
for (int k=n/2;k>=1;k--)
sink(a,k,n);
while(n>1){
exch(a,1,n--);
sink(a,1,n);
}
}
int main(){
int a[]={12,3,5,1,67,10,9.20};
int n=sizeof(a)/sizeof(int);
heapsort(a);
for (int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
but result it shows me looks like this
12 3 5 1 67 10 9 Press any key to continue . . .
also look that in my array total number is 8 and here it shows me 7 as output, i think core of this problem should be this
1>c:\users\datuashvili\documents\visual studio 2010\projects\heap\heap\heap.cpp(36): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
it seams that possible loss of data while converting from double to int force code works incorrectly,am i correct or wrong?please help me
You wrote a . instead of a , between the 9 and 20:
int a[]={12,3,5,1,67,10,9.20};
This results in 7 numbers, the last of which is the double 9.20 which gets converted to an int.
Additionally, this code is wrong:
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
Array arguments are actually passed as pointers, so sizeof(a) won't give you the correct result. You should pass in the array size as an additional parameter instead.
One problem I can see immediately is here:
void heapsort(int a[]){
int n=sizeof(a)/sizeof(int);
You cannot pass an entire array as a parameter to a function in C/C++. The parameter syntax int a[] is, of course, confusing, but in fact it's equivalent to int* a. heapsort() can't know the size of the array to which a points. You have to pass the size in as a separate parameter.
In addition to all the other comments (sizeof(a), passing [] as arguments, having a . in the init-list), you want to write C++-code, right? But it looks quite C'ish, except for the iostream. Thereore:
use std::vector<int> from #include <vector> (add elements with push_back for example)
pass it as as a reference, i.e. void heapsort(std::vector<int> &a)
consider using std::swap( a[i], a[j] ); instead of exch

c++ pass auto matrix to function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I use arrays in C++?
i have a problem.
i have to use auto darray(matrix).
const int size_m=10;
const int size_n=10;
void process(int *x)
{
//i can pass array, all is well, i work as with dynamic allocated array
for(int i=0;i<size_m;scanf("%d",&x[i]),i++);
}
void input_m(int **x)
/*
mistake is here,
a cause of my problem that i'm trying to work with matrix allocated in stack(auto matrix,local) as with dynamically allocated matrix.
i receive error like this : "cannot convert ‘int [100][100]’ to ‘int**’ in assignment" how should i pass it?
*/
{
for(int i=0;i<size_m;i++)
for(int j=0;j<size_n;j++)
scanf("%d",&x[i][j]);
}
int main()
{
int x[size_m];
input(x);
int matr_x[size_m][size_n];
input_m(matr_x);
return 0;
}
THANK YOU! it works.. it was so simple, as usual)
const int sizem=3;
const int sizen=3;
void _input(int x[sizem][sizen])
{
for(int i=0;i<sizem;i++)
for(int j=0;j<sizen;x[i][j]=1,j++);
}
int main()
{
int m=10,n=10;
int x[sizem][sizen]={{1,2,3},{5,7,4}};
_input(x);
for(int i=0;i<sizem;i++)
{ for(int j=0;j<sizen;printf(" %d",x[i][j]),j++);
puts("");
}
puts("");
return 0;
}
Your two-dimensional array is incompatible with the function you wrote for fundamental reasons of how memory works in C.
When you write int matrix[size_m][size_n] you are telling the compiler that you want a block of sizeof(int)*size_m*size_n bytes and you intend to store integers in it.
When you write int ** x you are telling the compiler that x is a pointer to a pointer to an integer. If you want to use x as a two-dimensional array, then x should point to not just one pointer, but the first pointer in an array of pointers, i.e. a contiguous region of memory that contains pointers for each row of your matrix. But you don't have any such array of pointers anywhere in the program you posted.
Since you know the dimensions of your matrix at compile time, you can fix this by changing the type of x be int x[size_m][size_n]. Better yet, make a typedef:
typedef int MyMatrix[size_m][size_n];
void input_m(MyMatrix x){ ... }
int main()
{
MyMatrix matr_x;
...
}
First of all, see the answer to this question. Your code should compile if you change void input_m(int **x) to void input_m(int x[size_m][size_n]) (assuming that both size_m and size_n are constants). Note that, as stated in the question that I linked to, "in general, to pass 2D arrays to functions you need to specify the array dimensions for all but the first dimension."