在函数的址传递过程中,都应该习惯性考虑做空指针判断,否则很容易出现莫名奇妙的问题。这次就是因为忘了这茬导致半天找不到问题所在,做个文章警醒一下自己,也提醒大家注意这些小细节
如下图:
实际上是因为是因为忘了做空指针判断,加上之后问题解决:
#include <iostream>
using namespace std;
int* test(int count)
{
int* p = (int*)malloc(sizeof(int) * count);
if (!p)
{
cout << "p is null" << endl;
}
else
{
*(p + 0) = 5;
}
return p;
}
int main()
{
int* p = test(3);
*(p + 1) = 6;
*(p + 2) = 7;
for (int i = 0; i < 3; i++)
{
cout << *(p + i) << endl;
}
free(p);
return 0;
}
参考:https://blog.csdn.net/qq_41649549/article/details/118927224