-2

So I am trying to edit an int variable from the main inside a function. When I define the int variable at the main it gets an address but when I sent this int variable to the function it becomes NULL. this is my function call at the main:

    AB = intersect(A, groupLengthA, B, groupLengthB, AB, &groupLengthAB);

this is my function:

int* intersect(int* A, int sizeA, int* B, int sizeB,int* sizeAB)
{ 

int i, j,k=0;
int* AB;

if (sizeA < sizeB)
{
    AB = (int*)malloc(sizeof(int)*sizeA);
    if (AB == NULL)
    {
        printf("***Allocation ERROR***");
        return;
    }
}

else
{
    AB = (int*)malloc(sizeof(int)*sizeA);
    if (AB == NULL)
    {
        printf("***Allocation ERROR***");
        return;
    }
}



for (i = 0; i < sizeA; i++)
{
    for (j = 0; j  < sizeB; j ++)
    {
        if (*(A + i) == *(B + j))
        {

            *(AB + k) = *(A + i);
            k++;
        }
    }
}

*sizeAB = k;
return AB;

}

When I gets from the the main the sizeAB it becomes NULL and therefor I can edit the values inside the pointer.

this is my main:

void main()
{
    //Variables
    int* A;
    int* B;
    int* AB = NULL;
    int groupLengthA, groupLengthB, i, groupLengthAB = 0 ;


    printf("Please enter the length of group A: \n");
    scanf("%d", &groupLengthA);

    printf("Please enter the length of group B: \n");
    scanf("%d", &groupLengthB);

    A = (int*)calloc(groupLengthA, sizeof(int));
    if (A == NULL)
    {
        printf("***Allocation ERROR***");
            return;
    }

    B = (int*)calloc(groupLengthB, sizeof(int));
    if (B == NULL)
    {
        printf("***Allocation ERROR***");
        return;
    }


    printf("Please fill the content of group A: \n");
    for (i = 0; i < groupLengthA ; i++)
    {
        scanf("%d", (A + i));
    }

    printf("Please fill the content of group B: \n");
    for (i = 0; i < groupLengthB; i++)
    {
        scanf("%d", (B + i));
    }

    printf("Group A: ");
    for (i = 0; i < groupLengthA; i++)
    {
        printf("[%d] ", *(A + i));
    }

    printf("\n");
    printf("Group B: ");
    for (i = 0; i < groupLengthB; i++)
    {
        printf("[%d] ", *(B + i));
    }

    AB = intersect(A, groupLengthA, B, groupLengthB, AB, &groupLengthAB);

        for (i = 0; i < groupLengthAB; i++)
        {
            printf("%d", *(AB + i));
        }

1 Answers1

0

The problem is how you call.. You have 5 arguments in function intersect but you call it with 6.

Change it as

AB = intersect(A, groupLengthA, B, groupLengthB, &groupLengthAB);

Optional change

Your if and else in function intersect do the same thing.

You can change the way you allocate memory in else as

AB = (int*)malloc(sizeof(int)*sizeB);

Basically you are trying to allocate minimum(sizeA,sizeB) bytes.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79