0
#include <iostream>
using namespace std;

int add(int a, int b)
{
    int sum = a + b;
    return sum;
}

char* print()
{
    char arr[] = "Hello";
    char buffer[6];
    strcpy_s(buffer,arr);
    return buffer;
}

int main(){
    cout << add(2,3)<< endl;    // This prints "5"
    cout << print() <<endl;     // This prints junk!!!! 
}

1) add(2,3) print 5, how the value is ratained in this case considering print() function which returns pointer

2) Where 2 functions stored. Both will be stored in stack i guess, Why is print() function isnot printing "Hello" then

Vijay M M
  • 81
  • 6
  • What exactly is your question? Your title and two bullets conflict. The memory would be stack because you aren't dynamically allocating memory. – TimLayne Aug 10 '16 at 03:06
  • My question is why in first case(cout statement) it prints 5. And in second cout it prints junk value. I was expecting "Hello" – Vijay M M Aug 10 '16 at 03:12
  • 4
    Trying to return an array won't work as you think. Also this is a duplicate try going to this question: http://stackoverflow.com/questions/5157439/why-doesnt-c-support-functions-returning-arrays . – TimLayne Aug 10 '16 at 03:58
  • @TimLayne Thank you, That helps :) – Vijay M M Aug 10 '16 at 05:14
  • Possible duplicate of [Why doesn't C++ support functions returning arrays?](https://stackoverflow.com/questions/5157439/why-doesnt-c-support-functions-returning-arrays) – barbsan May 22 '19 at 13:07

0 Answers0