-2

I am trying to create a simple function to parse an array and to copy it into another array. All the values inside an interval. Here is the code:

#include<stdio.h>
#define LEN 5

int* vediValori(int *valori, int inf, int sup, float *media);

int main()
{
    int val[LEN] = {10,20,30,40,50}, inf, sup, *valScelti = NULL;
    float media = 0.0;

    printf("Inserisci estremo inferiore: ");
    scanf("%d", &inf);

    printf("Inserisci estremo superiore: ");
    scanf("%d", &sup);

    printf("\nVerranno ora isolati tutti i valori compresi fra gli estremi...\n");

    valScelti = vediValori(val, inf, sup, &media);

    printf("\nNUOVO VETTORE CREATO:\n\n");

    for(int i = 0; i < LEN; i++)
    {
        printf("%d\n", valScelti[i]);
    }
}

int* vediValori(int *valori, int inf, int sup, float *media)
{
    int *tmp, i = 0, j = 0;

    while(i < LEN)
    {
        if(*(valori+i) >= inf && *(valori+i) <= sup)
        {
            *(tmp+j) = *(valori+i);
            *media += *(valori+i);

            j++;
        }
        i++;
    }

    return tmp;
}

Why is this not working? Where is it incorrect ??? Any help will be appreciated thanks :)

Cal
  • 1

1 Answers1

-1

You are not allocation memory to tmp in vediValori function.

int* vediValori(int *valori, int inf, int sup, float *media)
{
    //Edit: No need to type-case `void *` returned by malloc so
    int *tmp = malloc(sizeof(int)*(sup-inf)), i = 0, j = 0;

    //int *tmp = (int *)malloc(sizeof(int)*(sup-inf)), i = 0, j = 0;
    //            /\
    //          Not Needed   

while(i < LEN)
{
    if(*(valori+i) >= inf && *(valori+i) <= sup)
    {
        *(tmp+j) = *(valori+i);
        *media += *(valori+i);

        j++;
    }
    i++;
}

return tmp;
}

This might work Credits melpomene and this

Community
  • 1
  • 1
Sniper
  • 1,428
  • 1
  • 12
  • 28