in this code i am trying to convert a 2d array into 1d array. I have declared the 1d array inside the function newarr(). i am unable to return the address of array arr to the main function so that I can print it.this is getting resolved if I dynamically make the array inside the function newarr().why does it happen. why cannot i initialise the array with int arr[9] inside newarr().
#include<iostream>
using namespace std;
int *newarr(int a[][3]);
void printarr(int arr[]);
int main()
{ int i,j,z=0;
int* q;
int a[3][3];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
q=newarr(a);
cout<<"new array"<<endl;
printarr(q);
}
int *newarr(int a[3][3])
{ int i,j,z=0;
int arr[9];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr[z]=a[i][j];
z++;
}
}
return arr;
}
void printarr(int *arr)
{ int i;
for(i=0;i<9;i++)
{
cout<<arr[i]<<" ";
}
}
This is happing because you declared arr inside a function which means it is local to that function. Space for arr will get deleted as soon as your function returns (or exits) and hence your returned address become invalid.
On thing you try other than dynamically allocating is declaring it as static inside function
Example:-
static int arr[9];
Space for static variable doesn't get deleted when function returns.
You cannot return address of local variable.
arr
is a local variable of function newarr
, It is stored in stack.
You have four simple ways to fix this.
int *newarr(int a[3][3]){
int i,j,z=0;
// int arr[9];
int *arr = new int[9];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr[z]=a[i][j];
z++;
}
}
return arr;
}
Don't for get to free the memory or a memory leak will occur.
int *newarr(int a[3][3], int *arr){
int i,j,z=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr[z]=a[i][j];
z++;
}
}
return arr;
}
and you can call the function like:
int arr[9];
newarr(a, arr);
printArray(arr);
int arr[9];
int *newarr(int a[3][3]){
int i,j,z=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr[z]=a[i][j];
z++;
}
}
return arr;
}
int *newarr(int a[3][3]){
static int arr[9];
int i,j,z=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr[z]=a[i][j];
z++;
}
}
return arr;
}
For more details visit: How to access a local variable from a different function using pointers?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.