I'm trying to learn how to use C (from C#) and malloc has been one of the things giving me trouble when it comes to arrays. I have a pretty simple function to take an array sorted in non-descending { -1, 0, 1, 2, 3} ) order, and its size, square each value, and sort it in ascending order based on the squared values.
/// <param name="nums">integer array nums</param>
/// <param name="size">Size of array</param>
/// <returns>Sorted and squared array</returns>
int *sortedSquaredArray(int* nums, int size)
{
//Starting from both ends of the array, square and do a semi-merge sort
int *sortedArray = (int *)malloc(size * sizeof(int));
int startIdx = 0;
int endIdx = size - 1;
int cnt = size - 1;
int a;
int b;
int c;
while (startIdx < endIdx)
{
a = nums[startIdx] * nums[startIdx];
b = nums[endIdx] * nums[endIdx];
if (a >= b)
{
sortedArray[cnt] = a;
startIdx += 1;
}
else
{
sortedArray[cnt] = b;
endIdx += 1;
}
cnt -= 1;
}
//final loop
c = nums[startIdx] * nums[startIdx];
sortedArray[0] = c;
return sortedArray;
When I pass the array back and try to print it (I'm in the console on Visual Studio) only the final value is set correctly in the sortedArray, which makes me think I'm writing to totally the wrong memory addresses, but I'm not sure why. I'm also not really clear when, if you pass the pointer back to another function, to free up the used memory from malloc.
/// Run the sortedSquaredArray test
/// </summary>
void runSortedSquaredArrayTest()
{
int nums1[] = { -4, -1, 0, 3, 10 };
int *res = sortedSquaredArray(nums1, 5);
printf("val1 %d, val2 %d, val3 %d, val4 %d, val5 %d", res[0], res[1], res[2], res[3], res[4]);
}
I feel like an idiot for taking something as neat as being able to actually manually allocate the memory and making such a mess of it :/