function返回指向int的指针

Kev*_*ith 4 c++ pointers

当调用add(4)时,我的main()在下面崩溃.

据我所知int*add,它应该返回一个指向整数的指针.然后,我应该能够主要说:

int*a = add(3);

返回指向int的指针.

请解释我做错了什么.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 8

问题是你已经声明了一个int*但没有给它指出任何东西.你需要做的是用一个内存位置初始化它(省略错误检查)

int* c = new int();
...
*c = d;  // Now works
Run Code Online (Sandbox Code Playgroud)

稍后虽然你需要确保释放这个内存,因为它是一个已分配的资源.

但更好的解决方案是使用引用.指针具有几个令人讨厌的属性,包括单元化值,NULL需要释放等等......其中大多数都不存在于引用中.以下是在此方案中如何使用引用的示例.

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

int c;
add(4, c);
Run Code Online (Sandbox Code Playgroud)


sha*_*oth 5

In

 *c = d;
Run Code Online (Sandbox Code Playgroud)

the pointer c is not initialized, so your program runs into undefined behavior. You could do something like the following instead:

void add( int what, int* toWhat )
{
    (*toWhat) += what;
}
Run Code Online (Sandbox Code Playgroud)

and call it like this:

int initialValue = ...;
add( 4, &initialValue );
Run Code Online (Sandbox Code Playgroud)