Error with pointers

Hi,
I am a newbee just started to learn C++. After reading the chapter on pointers I decided to play around with pointers & have written this code to basically read & write an array using pointers to transfer the array between functions.

This code is compiling fine without any warnings or errors. But when I run this, the function "output_data" isn't writing the same array which has been entered in "read_data" function.

Can someone please point out where I'm doing wrong?

Thanks...

Regards,
Odyssey

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;

int* read_data(int);
void output_data(int*,int);

int main()
{
    //defining the data variables
    int closing_price[100];
    int no_data;
    
    //defining the pointers to the data variables
    int* p_cl_pr;
    p_cl_pr=closing_price;

    //starting the data entry process
    cout<<"Enter the number of price data you have: ";
    cin>>no_data;
    cout<<endl;
    cout<<"----------------------------------------------"<<endl;
    p_cl_pr=read_data(no_data);
    
    //the code for the data output process
    output_data(p_cl_pr,no_data);
    return 0;
}

//function to take care of data entry
int* read_data(int n)
{
    int array[n];
    int* p;
    p=array;
    cout<<"\nEnter the data points one by one below:"<<endl;
    for(int i=0;i<n;i++)
    {
	cout<<"Closing Price ["<<i<<"]=";
	cin>>array[i];
    }
    return (p);
}

//function to take care of data output
void output_data(int* a,int n)
{
    cout<<"-----------------------------------------------------"<<endl;
    cout<<"The array that you have entered is:"<<endl;
    for(int i=0;i<n;i++)
	cout<<"Array["<<i<<"]="<<*(a+i)<<endl;
}

You are declaring an integer array local to the read_data function and returning its address. But one the function resolves all locally created data is destroyed. You need to use the new keyword to create data on the free store so you can still access it outside the function.
Hi pogrady, thanks a lot. That solved the problem perfectly..
Topic archived. No new replies allowed.