Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function returns pointer to int

Tags:

c++

pointers

My main() crashes below when add(4) is called.

As I understand int* add, it should return a pointer to integer. Then, I should be able in main to say:

int * a = add(3);

to return a pointer to int.

Please explain what I'm doing wrong.

#include <cstdlib>
#include <iostream>

using namespace std;

int* add (int a) {
   int * c, d;
   d = a + 1;
   *c = d;
   cout << "c = " << c << endl; 
   return c;
}

int main(int argc, char *argv[])
{
    int a = 4;

    int * c;

    c = add(4); 

    system("PAUSE");
    return EXIT_SUCCESS;
}
like image 808
Kevin Meredith Avatar asked Dec 03 '22 11:12

Kevin Meredith


1 Answers

The problem is that you have declared an int* but not given it anything to point to. What you need to do is initialize it with a memory location (error checknig omitted)

int* c = new int();
...
*c = d;  // Now works

Later on though you'll need to make sure to free this memory since it's an allocated resource.

A better solution though is to use references. Pointers have several nasty attributes including unitialized values, NULL, need to free, etc ... Most of which aren't present on references. Here is an example of how to use references in this scenario.

void add (int a, int& c) {
   int d;
   d = a + 1;
   c = d;
   cout << "c = " << c << endl; 
}

int c;
add(4, c);
like image 71
JaredPar Avatar answered Dec 29 '22 10:12

JaredPar