The following is a problem taken from leetcode: Two Sum problem, where a specific target value should be achieved from the sum of any 2 elements in the array and the indices of the two elements should be stored in the return array which should be malloced and returned.
I am getting an error as 'ret is redeclared as different kind of symbol'.
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *twoSum(int *nums, int numsSize, int target, int *ret) {
int i, j;
int *ret = (int *)malloc(sizeof(int) * 2);
for (i = 0; i < numsSize; i++) {
for (j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
ret[0] = i;
ret[1] = j;
}
}
}
return ret;
}
retand then you also define the local variableret. Remove one of them.int* ret=(int*)malloc(sizeof(int)*2);1) be sure to have the statement:#include <stdlib.h>2) the returned type isvoid*which can be assigned to any pointer. Casting just clutters the code and is error prone. Suggest removing that cast. 3) always check (!=NULL) the returned value to assure the operation was successful. If not successful (==NULL) then callperror( "Your error message" );to output both your error message and the text reason the system thinks the error occurred tostderr.for(i=0;i<numsSize;i++)Suggest limiting thisfor()loop to:for( i=0; i< (numsSize-1); i++ )so as to avoid the variablejbeing equal tonumsSizefor one iteration of the inner loop. Such a value forjcausesnums[j]to access beyond the end of the arraynums[]resulting in undefined behavior ( and possibly a seg fault event )int i,j;This is setting the 'scope' of those variables tofile scope. However, good programming practice is to limit the 'scope' of variables . Suggest removing that line and modifying:for(i=0;i<numsSize;i++)tofor( int i=0; i<numsSize; i++ ). Similar considerations apply to the statement:for(j=i+1;j<numsSize;j++). Also, note the use of appropriate horizontal spacing for readability. The compiler doesn't care but humans do care about readability.