0

Here is a code it print only single value If I want to print whole array it does not work well.

#include <iostream>
using namespace std;

int *firstDay(int fd)
{

int d[35] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int setday = 1;
int *pnd;
pnd = d;

int limit = 35 - fd;

for(fd;fd<limit;fd++)
{
    d[fd] = setday;
    setday++;
}
return pnd;
  }

 void display(int *d)
{
cout<<d[1]<<endl;  // value 0
cout<<d[2]<<endl;  // value 1
cout<<d[3];        // value 2
 }

 int main()
 {
display(firstDay(2));
return 0;
 }

If I write only one cout then it works and print correct value If I use more then one cout then it can not print correct value.

user3211303
  • 11
  • 1
  • 1
  • 3

1 Answers1

0

firstDay is returning a pointer into an array declared inside the function; this pointer is invalidated as soon as the function returns and your attempts to dereference it result in undefined behaviour.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • If I use one `cout` for any value it print its value it mean `firstday` return all array then why it does not work. – user3211303 Jan 26 '14 at 07:56