238. Product of Array Except Self C语言
来源:互联网 发布:简述liunx下的串口编程 编辑:程序博客网 时间:2024/06/05 17:45
不会申请空间,不会free,我这个错误的代码总是显示[ ],就是什么也不显示
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* productExceptSelf(int* nums, int numsSize, int* returnSize) { int front[numsSize]; int back[numsSize]; front[0]=1; *returnSize=(int)malloc(numsSize*sizeof(int)); back[numsSize-1]=1; for(int i=0;i<numsSize-1;i++){ front[i+1]=front[i]*nums[i]; } for(int i=numsSize-1;i>0;i--){ back[i-1]=back[i]*nums[i]; } for(int i=0;i<numsSize;i++){ returnSize[i]=front[i]*back[i]; } return returnSize;}
returnSize是指针,感觉应该定义一个数组存储结果,但是不知道应该返回returnSize还是数组
弄明白了 柏宁真好
形参*returnSize表示一个指针,传进来的是一个地址,我需要在这个地址指向的地方写上有多少个值(就是最终结果有多少个)
我还需要在子函数里面自己定义一个数组,用来存储front和back乘积后最终的结果,这个数组的大小就是returnSize里面的值
返回值时返回这个数组,因为returnSize已经定义了大小,地址指向的位置已经有数据了,就算子函数不返回returnSize,里面的值也已经被写入了
系统的主程序就知道从我返回的数组里面取多少值了
Get it!
实践出真知,柏宁说
int front[numsSize];int back[numsSize];
这种是数组静态申请空间的意思,但是numsSize是变量,不能静态申请空间
动态申请空间的方法是
int *front;
front=(int *)malloc(numsSize*sizeof(nt));
申请个指针,然后动态申请空间,因为默认定义指向的数据是void类型,所以前面用(int *)强制转换成int
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* productExceptSelf(int* nums, int numsSize, int* returnSize) { *returnSize = numsSize;//指针指向的值的赋值方法 int *result; int *front; int *back; result = (int *)malloc(numsSize*sizeof(int)); front = (int *)malloc(numsSize*sizeof(int)); back = (int *)malloc(numsSize*sizeof(int)); front[0] = 1; back[numsSize-1] = 1; for(int i=0;i<numsSize-1;i++){ front[i+1]=front[i]*nums[i]; } for(int i=numsSize-1;i>0;i--){ back[i-1]=back[i]*nums[i]; } for(int i=0;i<numsSize;i++){ result[i]=front[i]*back[i]; } return result;}哈哈哈哈哈 仰天大笑出门去!!
0 0
- 238. Product of Array Except Self c语言
- 238. Product of Array Except Self C语言
- [leetcode-238]Product of Array Except Self(C语言)
- LeetCode 238. Product of Array Except Self 题解(C++)
- 238. Product of Array Except Self (C++)
- [leetcode] 238.Product of Array Except Self
- [LeetCode]238.Product of Array Except Self
- [leetcode] 238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self
- Linux平台 Oracle 11gR2 RAC安装Part3:DB安装
- mac上TK Framework double implementation
- 数据结构与算法之查找
- Android studio 2.2 使用 cmake 编译 libpng
- call by value or reference
- 238. Product of Array Except Self C语言
- UVA 12093 树形DP
- setContentView与LayoutInflater加载解析机制原理
- Linux下基于TCP的文件传输
- guava之Multimap
- 暴力求解-枚举法
- node.js+formidable
- 求导公式
- html视频教程全套