我是靠谱客的博主 个性白猫,这篇文章主要介绍力扣遇到两个数之和时的问题,现在分享给大家,希望可以做个参考。

今天在刷力扣时遇到一个小问题,记录下来,防止自己忘记。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target) { int x[2]={0}; for(int i=0;i<numsSize;i++){ for(int j=i+1;j<numsSize;j++){ if(target==nums[i]+nums[j]){ x[0]=i; x[1]=j; return x; } } } return 0; } 遇到了错误提示:***__SerializerHelper__.inl:10:10: runtime error: load of null pointer of type 'const int'*** 我网上百度了一下,原来 **在调用函数时,如果返回值如果是一个常量则没问题。如果返回值若为指针则可能会出现该错误,假如返回的指针地址指向函数内的局部变量,在函数退出时,该变量的存储空间会被销毁,此时去访问该地址就会出现这个错误**。我的理解是因为int x[2]是一个局部变量,当return x时,x就会被释放当i继续循环的时候,指针访问时其空间已经被销毁,所以我们将下x[]变成一个全局变量就可以了`/* * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target) { static x[2]={0}; for(int i=0;i<numsSize;i++){ for(int j=i+1;j<numsSize;j++){ if(target==nums[i]+nums[j]){ x[0]=i; x[1]=j; return x; } } } return 0; } 这样就可以通过测试了。 小白基础薄弱,希望看到此篇的前辈指点一下,看看我是否理解正确?`

最后

以上就是个性白猫最近收集整理的关于力扣遇到两个数之和时的问题的全部内容,更多相关力扣遇到两个数之和时内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部