printing an array

Im trying to have a dynamically allocated array, where everytime the pr_create function is called, the array grows in size by one, and a new variable is assigned to that new space. but whenever i call the pr_browse function, only the most recently entered name is printed. (full source code in link) thanks!
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
void pr_create();
void pr_create()
{
    acc_num = 0;
    total_a ++;
    
    cout<<"enter first name:"<<endl;
    string temp_fn;
    cin>>temp_fn;
    

    fn_ar = new string[total_a];
    fn_ar[acc_num] = temp_fn;
    acc_num ++;
    
}

void pr_browse();
void pr_browse()
{
    for (int i = 0; i <= acc_num; i++)
    {
        cout<<fn_ar[i]<<endl;    
    }
    
}


full code:
http://codepad.org/vduyPo1z
Every time you call pr_create(), you allocate memory for a whole new array You then only set the value of the final first element in the array:

1
2
    fn_ar = new string[total_a];
    fn_ar[acc_num] = temp_fn;


This means that only the element with index acc_num of the array pointed to by fn_ar will have valid data. Every other element will have an undefined value.

What is fn_ar? A global variable?
Last edited on
You need to read up on memory scope. Why are you declaring functions and then immediately defining them? That's obnoxious. You are resetting 'acc_num' every time you call this function so you're only ever writing to the first element in the array. You're also not doing anything to copy the old data to the new array.
can i also add, you dont need to do this at all:

1
2
3
4
5
6
void pr_browse();
void pr_browse()
{

...
}


so remove any method declarations if your implementation directly follows.


I also see you new'ing up a string, but not freeing up that memory at all.
about this...
void pr_browse();
void pr_browse()
{

}

whenever I don't declare the function before i define it, Xcode gives me an error:

no prototype for function

Topic archived. No new replies allowed.