在函數的址傳遞過程中,都應該習慣性考慮做空指針判斷,否則很容易出現莫名奇妙的問題。這次就是因為忘了這茬導致半天找不到問題所在,做個文章警醒一下自己,也提醒大家注意這些小細節
如下圖:
實際上是因為是因為忘了做空指針判斷,加上之后問題解決:
#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