how to call pointer function

Advertisements

please tell me how to call the function twoSum bellow,it has the int* ,I do not know how to do that .thank you .

#include <stdio.h>

//int twoSum(nums, target);
int main() {
    printf("Hello, World!\n");
    int nums[10]= {2,7,11,15};
    int target = 9;
    int numsSize=3;
    int retrunSize=3;
    int a=twoSum(nums,numsSize,target,retrunSize);
    return 0;
}

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    for (int i = 0; i < numsSize; ++i) {
        for (int j = i + 1; j < numsSize; ++j) {
            if (nums[i] + nums[j] == target) {
                int* ret = malloc(sizeof(int) * 2);
                ret[0] = i, ret[1] = j;
                *returnSize = 2;
                return ret;
            }
        }
    }

    *returnSize = 0;
    return NULL;
}

>Solution :

You can refer below, PS: my code is not in proper standard.

 #include <stdio.h>
 #include <stdlib.h>
 
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    for (int i = 0; i < numsSize; ++i) {
        for (int j = i + 1; j < numsSize; ++j) {
            if (nums[i] + nums[j] == target) {
                int* ret = malloc(sizeof(int) * 2);
                ret[0] = i, ret[1] = j;
                *returnSize = 2;
                return ret;
            }
        }
    }
    *returnSize = 0;
    return NULL;
}
 
    //int twoSum(nums, target);
    int main() {
        printf("Hello, World!\n");
        int i;
        int* (*funptr)(int*, int, int, int*) = &twoSum;
        int nums[10] = {2,7,11,15};
        int target = 9;
        int *returnSize = malloc(sizeof(int));
        int *a=(*funptr)(nums, 10, target, returnSize);
        printf("returnSize = %d\n", *returnSize);
        printf("Nums porsition are: ");
        for (i = 0; i < *returnSize; i++) {
            printf ("a[%d] = %d ", i, a[i]);
        }
        return 0;
    
    }

Leave a ReplyCancel reply