Double Pointer Using Error - c

I am having a trouble while practicing double pointer
The Error is "EXE_BAD_ACCESS" in Xcode
#include <stdio.h>
/* Program to Get Min and Max Value
in Array */
void SaveValue(int **maxPtr, int **minPtr, int arr[])
{
int i;
**maxPtr=arr[0]; // Error Line
**minPtr=arr[0]; // Error Line
for(i=1; i<5; i++)
{
if(arr[i]>**maxPtr)
**maxPtr=arr[i];
else if(arr[i]<**minPtr)
**minPtr=arr[i];
}
}
int main()
{
int arr[5]={4, 5, 7, 2, 6};
int *maxptr;
int *minptr;
SaveValue(&maxptr, &minptr, arr);
printf("%d, %d \n", *maxptr, *minptr);
}
I've thought that *dptr of **dptr = &ptr is *ptr
and **dptr means variable which *ptr pointing.
so I assume that **dptr = arr[0] means save first num of arr by reference at variable which *ptr pointing!
but I experiencing access error now.. I will thank for your help!

void SaveValue(int **maxPtr, int **minPtr, int arr[]); provides pointers to pointers to int so use them as such.
void SaveValue(int **maxPtr, int **minPtr, int arr[])
{
int i;
*maxPtr=arr + 0; /* same as *maxPtr = &arr[0]; */
*minPtr=arr + 0; /* same as *maxPtr = &arr[0]; */
for(i = 1; i < 5; i++)
{
if(arr[i] > **maxPtr)
*maxPtr = arr + i; /* same as *maxPtr = &arr[i]; */
else if(arr[i] < **minPtr)
*minPtr = arr + i; /* same as *minPtr = &arr[i]; */
}
}
Also this interface is a bit dangerous and unflexible; so why not pass the size of the array as well:
void SaveValue(int **maxPtr, int **minPtr, int arr[], ssize_t s)
{
*maxPtr=arr + 0;
*minPtr=arr + 0;
for(--s; s >= 0; --s)
{
if(arr[s] > **maxPtr)
{
*maxPtr = arr + s;
}
else if(arr[i] < **minPtr)
{
*minPtr = arr + s;
}
}
}
Call the fcuntion like this:
SaveValue(&maxptr, &minptr, arr, sizeof arr/sizeof *arr);
As the return value of the function is unused we could utlize it to apply some error inidication to allow the user of the function to write more stable code:
int SaveValue(int ** maxPtr, int ** minPtr, int arr[], ssize_t s)
{
int result = 0;
if ((NULL == arr) || (NULL == maxPtr) || (NULL == minPtr) || (0 > s))
{
result = -1;
errno = EINVAL;
}
else
{
*maxPtr=arr + 0;
*minPtr=arr + 0;
for(--s; s >= 0; --s)
{
if(arr[s] > **maxPtr)
{
*maxPtr = arr + s;
}
else if(arr[i] < **minPtr)
{
*minPtr = arr + s;
}
}
}
return result;
}
Use it like this:
#include <stdio.h>
int SaveValue(int ** maxPtr, int ** minPtr, int arr[], ssize_t s);
int main(void)
{
int arr[5]={4, 5, 7, 2, 6};
int *maxPtr;
int *minPtr;
int result = SaveValue(&maxPtr, &minPtr, arr, sizeof arr/sizeof *arr);
if (-1 == result)
{
perror("SaveValue() failed")
}
else
{
printf("%d, %d \n", *maxPtr, *minPtr);
}
}

The pointer should be pointing to valid memory location before dereferencing it else it will lead to undefined behavior. Below changes will fix your error.
int max;
int min;
int *maxptr = &max;
int *minptr = &min;
There is no need of double pointer here change your function prototype to
void SaveValue(int *maxPtr, int *minPtr, int arr[])
Have
int max;
int min;
in main() and call this API accordingly
SaveValue(&max,&min,arr);

I'll assume your code is purely for pointer learning purposes and not an attempt to implement this operation in a practical situation. So if you want to have maxptr and minptr in main() pointing to the maximum and minimum values in arr[], I think you should change your double pointer assignments from **maxPtr=arr[0] to *maxPtr=&arr[0], so your code would become:
void SaveValue(int **maxPtr, int **minPtr, int arr[])
{
int i;
*maxPtr = &arr[0]; // Error Line
*minPtr = &arr[0]; // Error Line
for (i = 1; i < 5; i++) {
if (arr[i] > **maxPtr)
*maxPtr = &arr[i];
else if (arr[i] < **minPtr)
*minPtr = &arr[i];
}
}
In this case, when you make the assignments, you don't want to dereference the double pointers. Instead, you should assign it with the address of the element you want to show when you dereference them in main().

You don't need to use the double asterisk when initialize the maxPtr and minPtr pointers in the function SaveValue, neither in the for loop body. MaxPtr and minPtr both are double pointers, but is still the memory direction of maxptr in main(). So you only need to dereference them with a single asterisk, to acces the memory direction them points to.
The source correct source code is this:
#include <stdio.h>
/* Correct program to Get Min and Max Value in Array */
void SaveValue(int **maxPtr, int **minPtr, int arr[])
{
int i;
*maxPtr=arr[0];
*minPtr=arr[0];
for(i=1; i<5; i++)
{
if(arr[i]>*maxPtr)
*maxPtr=arr[i];
else if(arr[i]<*minPtr)
*minPtr=arr[i];
}
}
int main(void)
{
int arr[5]={4, 5, 7, 2, 6};
int *maxptr;
int *minptr;
SaveValue(&maxptr, &minptr, arr);
printf("%d, %d \n", maxptr, minptr);
return 0;
}
When I compile it with GCC and execute it, i get the next output:
7, 2.
Remember that depending of the environment (Operating System, version, compiler, standards) that you use the program results may vary.

Related

what is the issue with copyArray func in this c program ? the copyArray function is not working properly

** I would like to copy the pointer array to a new pointer so the original array won't change**
/* The main contains a pointer (p) to an array */
int main()
{
...
...
...
p = (int*)malloc(length*sizeof(int));
z = (int*)copyArray(p, length);
printArray(z, length);
return 0;
}
/* end of main */
CopyArray func
/* copy the array, return a new pointer to a new array with same size and values */
int copyArray(int *p, int length)
{
int *z = (int*)malloc(length*sizeof(int));
for(length--; length>=0; length--)
{
z[length] = p[length];
}
return *z;
}
printArray func
/* The function receives a pointer to an array and it's length. it will print the values that the array contains by the order */
void printArray(int *p, int length)
{
int i = 0;
for(; i<length; i++)
{
printf("\n %d \n", p[i]);
}
}
Reason for not working : return *z; here you are returning only one element *(z+0) = z[0] not the whole array. Check the code below:
#include <stdio.h>
#include <stdlib.h>
int *copyArray(int *p, int length) // Change return type to `int *`
{
int *z = malloc(length * sizeof(int)); // No need to cast output of malloc
for (length--; length >= 0; length--)
{
z[length] = p[length];
}
return z; // return the pointer.
}
void printArray(int *p, int length)
{
int i = 0;
for (; i < length; i++)
{
printf("\n %d \n", p[i]);
}
}
int main()
{
int *p;
int *z;
int length =5;
p = malloc(length*sizeof(int)); // No need of casting
for(int i=0 ;i<length; i++)
{
p[i] = i; // assigning some values
}
z = copyArray(p, length); // Donot cast return of the function
printArray(z, length);
return 0;
}
The output is :
0
1
2
3
4

How to solve this error when trying to compute the twoSums coding question in C

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
#include<stdio.h>
int* twoSum(int* nums, int numsSize, int target);
int main(){
int*array;
int arraySize;
scanf("%d",&arraySize);
for (int i=0;i<arraySize;i++){
scanf("%d",&array[i]);
}
int target;
scanf("%d",&target);
int* positions=twoSum(array, arraySize, target);
printf("The positions are: %p",positions);
return 0;
}
int* twoSum(int* nums, int numsSize, int target){
int *returnSize = NULL;
for(int i=0,sum=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
sum =sum+nums[i]+nums[j];
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
else
returnSize[0]= -1;
returnSize[1]= -1;
}
}
return returnSize;
}
The error I am getting makes reference to a line that is empty in my code. Please help
there are mistakes in this code.First you should allocate memory for int*array; after taking int arraySize; as input , you can do it like this
array = malloc(sizeof(int) * arraySize);
then here %p is not appropriate , instead use %d. Take look here for more information about %p %p format specifier and also since you want to print 2 positions you need to call two arguments in printf like this printf("The positions are: %d %d", positions[0], positions[1]);
In your twoSum function , you need to allocate memory for int* returnSize ; like this returnSize = malloc(sizeof(int) * 2);
and here you are not returning positions of found elements , you are returning elements themselfs.
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
also you need to add return in this if-statement other wise , you will traverse array completely and returnSize elements will become -1 again(unless answer is too last element of array)
so this if should be like this:
if (sum == target) {
returnSize[0] = i;//num[i] is not position. it is element of array
returnSize[1] = j;//num[j] is not position .it is element of array
return returnSize;//otherwise it will traverse array compeltely and they -1 again
}
also only if you code one line for if,else,while,for,... (conditional statements) ,you can avoid using braces ,otherwise only one line of your code will executed ,if that condition become true ,so you have to add a block for this else:
else
{
returnSize[0] = -1;
returnSize[1] = -1;
}//coding more than one line so your else should be in a block
and also here sum=sum+num[i]+num[j]; is wrong you should change this to sum=num[i]+num[j]; because you only want to check sum of two current number ,or better way don't use sum at all only check equality of target with num[i]+num[j]
here is complete code:
int* twoSum(int* nums, int numsSize, int target);
int main() {
int* array;
int arraySize;
scanf("%d", &arraySize);
array = malloc(sizeof(int) * arraySize);//allocate memory for array
for (int i = 0; i < arraySize; i++) {
scanf("%d", &array[i]);
}
int target;
scanf("%d", &target);
int* positions = twoSum(array, arraySize, target);
printf("The positions are: %d %d", positions[0], positions[1]);//%p is for not for content of array
return 0;
}
int* twoSum(int* nums, int numsSize, int target) {
int* returnSize ;
returnSize = malloc(sizeof(int) * 2);
for (int i = 0; i < numsSize; i++) {
for (int j = 0; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
returnSize[0] = i;//num[i] is not position. it is element of array
returnSize[1] = j;//num[j] is not position .it is element of array
return returnSize;//otherwise it will traverse array compeltely and they -1 again
}
else
{
returnSize[0] = -1;
returnSize[1] = -1;
}//coding more than one line so your else should be in a block
}
}
return returnSize;
}
There is some mistakes in your code:
memory allocation
You declare pointers on int to store data to process and result, but you do not allocate memory: malloc is for Memory ALLOCation:
array = malloc(sizeof *array * arraySize);
and
int *returnSize = malloc(sizeof *returnSize * 2);
Sum calculation logic
sum value
In twoSum function, the sum variable is getting bigger and bigger: sum =sum+nums[i]+nums[j];
Instead, a simple if (target == nums[i] + nums[j]) will perform the test you wanted.
sum test
In your code, each time sum is not equal to target, you reset returnSize[0] to -1
You do not have to have an else clause: you can initialize the returnSize before the for loop.
missing {...}
Look at your first code: for any value of sum and target, returnSize[1] is set to -1 because you've forgotten to put accolades after the else (but, as written before, you do not even need an else)
gcc can warn you about such issue (-Wmisleading-indentation, or better -Wall)
for(int j=0;j<numsSize;j++){
sum =sum+nums[i]+nums[j];
if(sum==target){
returnSize[0]=nums[i];
returnSize[1]=nums[j];
}
else
returnSize[0]= -1;
returnSize[1]= -1;
}
Considering this, you can write a code that do what you wanted.
Be careful, you should test the scanf and malloc return values too...
#include <stdio.h>
#include <stdlib.h>
int *twoSum(int *nums, int numsSize, int target);
int main()
{
int *array;
int arraySize;
// TODO: test that scanf returned 1
scanf("%d", &arraySize);
// TODO: test that arraysize is at least 2
/* allocate array to store the numbers*/
array = malloc(sizeof *array * arraySize);
for (int i = 0; i < arraySize; i++) {
// TODO: test that scanf returned 1
scanf("%d", &array[i]);
}
int target;
// TODO: test that scanf returned 1
scanf("%d", &target);
int *positions = twoSum(array, arraySize, target);
printf("The positions are: %d(%d) %d(%d)\n", positions[0], array[positions[0]], positions[1], array[positions[1]]);
/* memory has been allocated? free it */
free(positions)
free(array)
return 0;
}
int *twoSum(int *nums, int numsSize, int target)
{
int *returnSize = malloc(sizeof *returnSize * 2);
returnSize[0] = returnSize[1] = -1;
for (int i = 0; i < numsSize; i++) {
for (int j = 0; j < numsSize; j++) {
if (target ==nums[i] + nums[j] ) {
returnSize[0] = i;
returnSize[1] = j;
return returnSize;
}
}
}
return returnSize;
}
Here your code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int* twoSum(int* nums, int numsSize, int target);
void print_pos(int * arr, int i) {
printf("test %d\n", i);
if (arr != NULL) {
printf("position 1 = %d, position 2 = %d\n", arr[0], arr[1]);
} else
printf("Not found\n");
}
int main(){
int array[5] = {5, 6, 2 ,1 ,3} ;
int target1 = 11, target2 = 9, target3 = 15;
int * positions1=twoSum(array, 5, target1);
int * positions2=twoSum(array, 5, target2);
int * positions3=twoSum(array, 5, target3);
print_pos(positions1, 1);
print_pos(positions2, 2);
print_pos(positions3, 3);
return 0;
}
int* twoSum(int* nums, int numsSize, int target){
int *return_arr = malloc(sizeof(int) * 2);
bool found = false;
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if((nums[i]+nums[j])==target){
return_arr[0]= i;
return_arr[1]= j;
found = true;
}
}
}
if (found)
return return_arr;
else {
free(return_arr);
return NULL;
}
}

Sort an array in the relative order of elements of another array in c

I wish to sort a second array as per the first array. e.g.
first = {1,8,7,2,4}
second = {9,7,2,10,3}
I want first to be unchanged and second to be sorted in the same relative order as the first. i.e. the lowest value is at index 0, the second lowest value is at index 3, third lowest value is at index 4 etc etc
second = {2,10,9,3,7}
I have already tried some code for the following
#include <stdio.h>
typedef struct
{
int num;
int pos;
}ArrType;
ArrType arrA[5] = {{1,0},{8,1},{7,2},{2,3},{4,4}};
ArrType arrB[5] = {{9,0},{7,1},{2,2},{10,3},{3,4}};;
int cmparr(const void *a, const void *b)
{
ArrType *tmpa, *tmpb;
tmpa = (ArrType*) a;
tmpb = (ArrType*) b;
return(arrA[tmpa->pos].num - arrA[tmpb->pos].num);
}
int main(void)
{
int i;
qsort(arrB,5, sizeof(ArrType), cmparr);
for (i=0; i<5; i++)
{
printf ("%d ",arrB[i].num);
}
return (0);
}
The actual output is
9 10 3 2 7
I am open to a different data structure, but arrB should only be sorted one time.
I have seen some solutions for this in C++, Javascipt and other languages. But there is not a solution in C.
Edit - These arrays would be quite large in the final program. I am looking for a single sorting operation. i.e. single call to qsort
You need to create the meta-data that matches the desired ordering (i.e an array of indexes). Then apply that meta-data to the second array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int first[] = {1,8,7,2,4};
int second[] = {9,7,2,10,3};
int compare(const void * a, const void * b);
int binary_search(int array[], int min, int max, int target);
void print_array(int * array, int c);
int main()
{
int idx;
int c = sizeof(first)/sizeof(int);
int * sorted = NULL;
int * indexes = NULL;
int * result = NULL;
if (NULL == (sorted = malloc(sizeof(first)))) {
return -1;
}
memcpy(sorted, first, sizeof(first));
if (NULL == (indexes = malloc(sizeof(first)))) {
free(sorted);
return -1;
}
memset(indexes, -1, sizeof(first));
if (NULL == (result = malloc(sizeof(second)))) {
free(sorted);
free(indexes);
return -1;
}
memset(result, -1, sizeof(second));
// 1st: Sort the reference array
qsort (sorted, c, sizeof(int), compare);
// 2nd: Record the position of each sorted element in the original array (this is your meta-data)
for (idx=0; idx<c; idx++) {
indexes[idx] = binary_search(sorted, 0, c, first[idx]);
}
// 3rd sort the target array
memcpy(sorted, second, sizeof(second));
qsort (sorted, c, sizeof(int), compare);
// 4th apply the stored positions to the sorted target array
for (idx = 0; idx < c; idx++) {
result[idx] = sorted[indexes[idx]];
}
print_array(result, c);
free(result);
free(indexes);
free(sorted);
return 0;
}
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int binary_search(int array[], int min, int max, int target)
{
int mid;
while (min <= max)
{
mid = min + (max - min)/2;
if (target > array[mid])
min = mid + 1;
else if (target < array[mid])
max = mid - 1;
else
return mid;
}
return -1;
}
void print_array(int * array, int c)
{
for(int i = 0; i < c; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
Demo
Here is my approach, it uses qsort twice and arrC contains the result.
#include <stdio.h>
typedef struct
{
int num;
int pos;
}ArrType;
ArrType arrA[5] = {{1,0},{8,1},{7,2},{2,3},{4,4}};
int arrB[5] = {9,7,2,10,3};;
int arrC[5];
int cmpInt(const void *a, const void *b)
{
return(*a - *b);
}
int cmp(const void *a, const void *b)
{
ArrType *tmpa, *tmpb;
tmpa = (ArrType*) a;
tmpb = (ArrType*) b;
return(tmpa->num - tmpb->num);
}
int main(void)
{
int i;
qsort(arrA,5, sizeof(ArrType), cmp);
qsort(arrB,5, sizeof(ArrType), cmpInt);
for (i=0; i<5; i++)
{
arrC[arrA[i].pos] = arrB[i];
}
return (0);
}
Since C doesn't have a lambda compare (which could be used to sort an array of indexes according to first[]), the code below sorts an array of pointers ap[] to the elements of first[] using qsort(). Using pointers eliminates the need to pass an array name as a parameter for the compare function, which in turn allows the compare function to work with qsort(). The expression (ap[i]-first) converts a pointer into an index. Next second[] is sorted, also using qsort(). Then ap[] is used as a set of ranks to reorder second[] in place and in O(n) time.
To explain reorder by rank versus reorder by index:
dst[rank[i]] = src[i]; /* reorder by rank */
dst[i] = src[index[i]]; /* reorder by index */
Example code:
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
/* compare for ptr to integer */
int cmppi(const void *p0, const void *p1){
return (*(int *)p0 - *(int *)p1);
}
/* compare for ptr to ptr to integer */
int cmpppi(const void *p0, const void *p1){
return (**(int **)p0 - **(int **)p1);
}
int main()
{
int first[] = {1, 8, 7, 2, 4};
int second[] = {9, 7, 2,10, 3};
int **ap; /* array of pointers */
int *tmpp;
int tmpi;
size_t i, j;
/* allocate and generate array of pointers to first[] */
ap = (int **)malloc(sizeof(first)/sizeof(first[0])*sizeof(int *));
for(i = 0; i < sizeof(first)/sizeof(first[0]); i++)
ap[i] = &first[i];
/* sort ap */
qsort(ap, sizeof(first)/sizeof(first[0]), sizeof(int *), cmpppi);
/* sort second */
qsort(second, sizeof(second)/sizeof(second[0]), sizeof(int), cmppi);
/* reorder ap and second in place using ap as rank (O(n) time) */
for (i = 0; i < sizeof(second) / sizeof(second[0]); i++){
while(i != (j = ap[i] - first)){
tmpp = ap[i]; /* swap(ap[i], ap[j]) */
ap[i] = ap[j];
ap[j] = tmpp;
tmpi = second[i]; /* swap(second[i], second[j] */
second[i] = second[j];
second[j] = tmpi;
}
}
/* display second[] */
for (i = 0; i < sizeof(second) / sizeof(second[0]); i++)
printf("%3d", second[i]);
printf("\n");
free(ap);
return 0;
}

Assign values to a pointer which was initialised to NULL before

Can someone tell me why do I get this segmentation fault?
Is it because I have set a pointer to NULL and passed it to a function?
Should I use arrays or pointers when I want to send an array to function?
#include <stdlib.h>
#include <stdio.h>
int* ComputeFibo(int _size);
void PrintFibo(int* _arr, int _size);
int main (int argc, char* argv[])
{
int* arr = NULL;
int n = 0;
printf("Please enter Fibonacci size:");
scanf("%d", &n);
arr = ComputeFibo(n);
PrintFibo(arr, n);
return 0;
}
int* ComputeFibo(int _size)
{
int sum = 0;
int indx = 0;
int* arr = NULL;
arr[indx] = 1;
for (indx = 1; indx < _size; ++indx)
{
arr[indx] = arr[indx - 1] + sum;
sum = arr[indx - 1];
}
return arr;
}
void PrintFibo(int* _arr, int _size)
{
int indx = 0;
for (; indx < _size; ++indx)
{
printf("%d\t", _arr[indx]);
}
}
I would love to get an answer with a good explanation for that.
The problematic statement is:
int* arr = NULL;
where arr is pointing at NULL and then you assign values to arr as if it's pointing to valid memory location.
You could fix it with:
int* arr = malloc(_size * sizeof *arr);
if (arr == NULL) { /* error *}
and then call free() on the returned pointer later.
arr = ComputeFibo(n);
PrintFibo(arr, n);
free(arr);
Also be aware that int can only represent limited values in C. So, for example, if you try to calculate upto 100 Fibonacci numbers, you are likely to run into integer overflow.
You tried to access index of a null pointer.
int* ComputeFibo(int _size)
{
int* arr = NULL;
arr[indx] = 1; //SIGF
...
}
I fixed your code if you want a reference.
#include <stdlib.h>
#include <stdio.h>
void compute_fibo(int *_arr, int _size);
void print_fibo(int *_arr, int _size);
int main(int argc, char *argv[]) {
int n = 0;
printf("Please enter Fibonacci size:");
scanf("%d", &n);
int *arr = (int *) malloc(sizeof(int) * n);
if (arr == NULL) return 1;
compute_fibo(arr, n);
print_fibo(arr, n);
free(arr);
return 0;
}
void compute_fibo(int *_arr, int _size) {
_arr[0] = 1;
_arr[1] = 1;
for (int index = 2; index < _size; index++) {
_arr[index] = _arr[index - 1] + _arr[index - 2];
}
}
void print_fibo(int *_arr, int _size) {
for (int index = 0; index < _size; ++index) {
printf("%d\t", _arr[index]);
}
}
output:
Please enter Fibonacci size:10
1 1 2 3 5 8 13 21 34 55

How to use memory allocation to store values in an array using pointers

I've written a code with a main body plus a function merge() that merges two arrays arr1[] and arr2[] and stores them in a third array, *arr3[].
I'm still confused by the pointers and memory allocation. What sort of command should I place in my code to tell it to put the two merged arrays into a third array, *arr3[]?
I tried writing *arr3 = (double *) malloc (*sz3) but I received an error "ld returned 1 exit status".
Here is the code:
/* This is a function that will merge contents of arr1 and arr2 and store in arr3 as a
pointer */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void merge(double arr1[], double arr2[], double *arr3[], int sz1, int sz2, int *sz3);
void print_arr(double arr[], int sz);
int main(){
double v0[] = {};
double v1[] = {22.0, 30.1, 35.2, 49.2, 56.4, 65.1, 76.4, 79.6, 86.2, 88.9};
double v2[] = {4.6, 9.0, 13.0, 47.8, 66.9, 68.7, 71.0};
double v3[] = {80.1, 92.7, 97.4, 102.3, 105.0, 112.3, 121, 136.7, 163.4, 177.9};
int sz1 = 10, sz2 = 7, sz3 = 10, szres;
double *res;
printf("\nTEST 1\n======\n");
merge(v1, v2, &res, sz1, sz2, &szres);
print_arr(res,szres);
free(res);
printf("\nTEST 2\n======\n");
merge(v0, v3, &res, 0, sz3, &szres);
print_arr(res,szres);
free(res);
printf("\nTEST 3\n======\n");
merge(v2, v3, &res, sz2, sz3, &szres);
print_arr(res,szres);
free(res);
return 0;
}
/* function to print the array */
void print_arr(double arr[], int sz){
for(int i = 0; i < sz; i++){
printf("%7.2lf",arr[i]);
}
printf("\n");
}
void merge(double arr1[], double arr2[], double *arr3[], int sz1, int sz2, int *sz3) {
int i, j, k;
j = k = 0;
for (i = 0; i < (sz1+sz2);) {
if(j < sz1 && k < sz2) {
if (arr1[j] < arr2[k]) {
*arr3[i] = arr1[j];
j++;
} else {
*arr3[i] = arr2[k];
k++;
}
i++;
} else if (j == sz1) {
for (; i < (sz1 + sz2);) {
*arr3[i] = arr2[k];
k++;
i++;
}
} else {
for (; i < (sz1+sz2);) {
*arr3[i] = arr1[j];
j++;
i++;
}
}
}
}
Two things:
The function parameter double *arr3[] is an array of double *. You're instead passing in a pointer to a double *, so you need to define it as double **arr3:
void merge(double arr1[], double arr2[], double **arr3, int sz1, int sz2, int *sz3) {
To properly allocate the right amount of memory, you need to first assign a value to *sz3. Then you can allocate space for that many doubles.
Right before the initial for loop in merge, add the following:
*sz3 = sz1+sz2;
*arr3 = malloc((*sz3) * sizeof(double));

Resources