This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I have tried to implement a simple function which returns the pointer to first element in array.
#include<iostream>
using namespace std;
int * func(int n)
{
int arr[n];
for (int a = 0; a <n; a++)
{
arr[a]=a;
}
return arr;
}
int main()
{
int n;
cin>>n;
int * arr=func(n);
for (int i = 0; i <n; i++)
{
cout<<*(arr+i)<<endl;
}
}
I have assumed that array occupies contiguous block of memory,then why the output of this program isn't what expected.
if n=10 then output is
0
-1216233191
-1215824576
-1215824576
-1215855028
-1215820256
-1074779464
-1215820256
-1074779464
134514382
int * func(int n)
{
int arr[n]; <<<<<<<<<<<<<<<local variable to this function.
for (int a = 0; a <n; a++)
{
arr[a]=a;
}
return arr;
}
You should not return address of local variables...
Related
This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
c++ void function not changing value of string [duplicate]
(2 answers)
Closed 1 year ago.
I fill vector with random numbers without repeating ones, but when I try to output them, the vector contains only 0s. I tried to clear it before the filling with func .clear() but then the program can't access particular elements in it. When I run the program with debugger it shows that vector contains some numbers, but when it run the func printing() it prints only 0s. I attached screenshots of my tries after code listing.
#include <iostream>
#include <vector>
void filling(std::vector<int> array, int size);
void printing(std::vector<int> array, int size);
int main()
{
srand(time(0));
int sizeA;
printf("Enter size of vector A: ");
std::cin >> sizeA;
std::vector<int> A (sizeA);
filling(A, sizeA);
printf("Vector A: \n\t");
printing(A, sizeA);
}
void filling(std::vector<int> vector, int size)
{
//filling vector without repeating numbers
int temp;
bool flag;
vector[0] = rand() % 31;
for (int i = 1; i < size; )
{
temp = rand() % 31;
flag = true;
for (int j = 0; j < size; j++)
{
if (vector[j] == temp)
{
flag = false;
break;
}
else
{
continue;
}
}
if (flag)
{
vector[i] = temp;
i++;
}
}
}
void printing(std::vector<int> vector, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", vector[i]);
}
}
This is the result I get but it's not what I expect:
Elements that debugger shows in vector after filling in the func:
Elements that shows after executing the func filling()
This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 3 months ago.
I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
for (int j = 0; j < n; j++)
{
cout << matrix[j];
}
}
int main()
{
int n,m;
cin>>n;
//int matrix[n]={};
DisplayBoard(matrix,n);
return 0;
}
i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
cout<<endl ;
for (int j = 0; j < n; j++)
{
cout << matrix[j]<<" ";
}
}
int main() {
int n,m;
cin>>n ;
int matrix[n];
for(int i=0;i<n;i++) {
cin>>matrix[i];
}
DisplayBoard(matrix,n);
return 0;
}
remember to declare array in main function too ,
that was one of your code error !
and this is incorrect to declare array :
int matrix[n]={} // incorrect !
Well. int matrix[n]={}; fills it with zeros and that's what I wanted to do. And my code with 1D array works fine but if I do it like so it does not.
#include <iostream>
using namespace std;
void DisplayMatrix(int matrix[][],int n,int m)
{
for(int i=0;i<n;i++)
{
for (int j = 0; j < m; j++)
{
cout << matrix[j];
}
}
}
int main()
{
int n,m;
cin>>n>>m;
int matrix[n][m]={};
DisplayMatrix(matrix,n,m);
return 0;
}
This question already has answers here:
Closed 10 years ago.
The following code is printing garbage values. I am passing an array to a function which adds 5 to every element, but when it returns that array's pointer, the main is showing garbage.
I have tried both indexing and pointers there in main but still same results. How can I fix this?
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int theArray[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
}
theArray is a local array in the function add5ToEveryElement() which you are returning to main(). This is undefined behaviour.
Minimally you can change this line:
int theArray[5];
to:
int *theArray = new int[5];
It'll work fine. Don't forget to delete it later in main(). SInce you modify the original pointer, save it:
int *arr = add5ToEveryElement(noArr, size);
int *org = arr;
// Rest of the code
//Finally
delete[] org;
Returning an array from a function is generally considered bad.
Unless you MUST have a "new" array, I would suggest the typical case in C and C++ is to modify the input array. If the CALLING function wants to have two separate arrays, then it can do so by making it's own copy. Alternatively, you could write your code to have two arrays passed into your function, e.g.
void add5ToEveryElement(int arr[], int arr2[], int size)
{
for(int i=0; i<size; i++)
{
arr2[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
}
then your main would call with two array arguments, and if you wish to use the same as input and output it will do that too.
Sure, this isn't exactly the answer to your question, but it gives a "better" solution to your problem.
I generally dislike allocation in functions - especially "hidden" allocation (this function says it's adding 5 to every element, not "allocate array with added 5 to each element". Code should never do surprising things, and allocating memory is a little bit of a surprise if you only asked for adding 5 to each element)
this is the perfect code
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int *theArray = new int[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
int *p = arr;
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
delete[] p;
}
This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 8 years ago.
Trying to make a program that sums 5 digit numbers by each digit. For some reason when I attempt to print individual elements of an array (one element at a time running 5 times) I get the correct value of 69134. But when I print them together:
int *addArray(int arr1[], int arr2[]){
int arrSum[5];
int r=0;
for(int i=4; i>=0; i--){
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
return arrSum;
}
int main(){
using namespace std;
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int *arrSum=addArray(data1,data2);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
I end up with the result 60000. Anyone know what is going on?
In addArray you are returning a pointer to a local variable (arrSum), which results in undefined behaviour. You should either pass in the result array from the calling function, or allocate the array dynamically. For example, using the first approach:
void addArray(const int arr1[], const int arr2[], int arrSum[])
{
int r=0;
for(int i=4; i>=0; i--)
{
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
}
int main()
{
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int arrSum[5];
addArray(data1,data2,arrSum);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Passing a pointer representing a 2D array to a function in C++
I am trying to pass my 2-dimensional array to a function through pointer and want to modify the values.
#include <stdio.h>
void func(int **ptr);
int main() {
int array[2][2] = {
{2, 5}, {3, 6}
};
func(array);
printf("%d", array[0][0]);
getch();
}
void func(int **ptr) {
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
ptr[i][j] = 8;
}
}
}
But the program crashes with this. What did I do wrong?
Your array is of type int[2][2] ("array of 2 array of 2 int") and its name will decay to a pointer to its first element which would be of type int(*)[2] ("pointer to array of 2 int"). So your func needs to take an argument of this type:
void func(int (*ptr)[2]);
// equivalently:
// void func(int ptr[][2]);
Alternatively, you can take a reference to the array type ("reference to array of 2 array of 2 int"):
void func(int (&ptr)[2][2]);
Make sure you change both the declaration and the definition.
It crashes because an array isn't a pointer to pointer, it will try reading array values as if they're pointers, but an array contains just the data without any pointer.
An array is all adjacent in memory, just accept a single pointer and do a cast when calling the function:
func((int*)array);
...
void func(int *ptr) {
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
ptr[i+j*2]=8;
}
}
}