简体   繁体   中英

Not responding my pointer function and not returning correct value

I am trying to make ac program where user will input 2 array and using pointer and user defined function. But it really not showing right answer. The main function will take the input from the user and it will send it to calculator function. where it will sum those array. And it will return the sum value to main function.

int calculator(int *my_array1, int *my_array2)
{
    int sum=0,sum1=0,sum2=0;
    for (int i = 0; i < strlen(my_array1); i++)
    {
        sum1+=(*(my_array1+i));
    }
    for (int i = 0; i < strlen(my_array2); i++)
    {
        sum2+=(*(my_array1+i));
    }
    sum=sum1+sum2;
    return sum;
}

int main()
{
    int size1,size2,i;
    printf("Enter First Array Size: ");
    scanf("%d",&size1);
    int array1[size1];
    printf("Enter Array's Value: ");
    for(i=0; i<size1; i++)
    {
        scanf("%d",&array1[i]);
    }
    printf("Enter Second Array Size: ");
    scanf("%d",&size2);
    int array2[size2];
    printf("Enter Array's Value: ");
    for(i=0; i<size2; i++)
    {
        scanf("%d",&array2[i]);
    }
    printf("\nSum: %d",calculator(array1,array2));
    return 0;
}

You can not use strlen for int* because it is not NULL terminated instead do this

#include<stdio.h>


int calculator(int *my_array1, int *my_array2,int len1,int len2)
{
    int sum=0,sum1=0,sum2=0;
    for (int i = 0; i < len1; i++)
    {
        sum1+=(*(my_array1+i));
    }
    for (int i = 0; i < len2; i++)
    {
        sum2+=(*(my_array1+i));
    }
    sum=sum1+sum2;
    return sum;
}

int main()
{
    int size1,size2,i;
    printf("Enter First Array Size: ");
    scanf("%d",&size1);
    int array1[size1];
    printf("Enter Array's Value: ");
    for(i=0; i<size1; i++)
    {
        scanf("%d",&array1[i]);
    }
    printf("Enter Second Array Size: ");
    scanf("%d",&size2);
    int array2[size2];
    printf("Enter Array's Value: ");
    for(i=0; i<size2; i++)
    {
        scanf("%d",&array2[i]);
    }
    printf("\nSum: %d",calculator(array1,array2,size1,size2));
    return 0;
}

Note: you are using variable length arrays it is in c99 only

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM