Dev
Dev

Reputation: 21

Return value of a function which had the data from a structure with typedef in c programming

Can someone help me why I'm not getting any output or return value for this code..?

// Arrays are already defined with this interface:
// typedef struct arr_##name {
//   int size;
//   type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
//   arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
//   return a;
// }
//
//
arr_float fareEstimator(int ride_time, int ride_distance, arr_float cost_per_minute, arr_float cost_per_mile) {
int i,len;
double t,d;
len=sizeof(cost_per_minute.arr)/sizeof(float);
arr_float fare[len];
for(i=0;i<len;i++)
{
    //t=ride_time*cost_per_minute.arr[i];
    //d=ride_distance*cost_per_mile.arr[i];
    fare->arr[i]=ride_time*cost_per_minute.arr[i]+ride_distance*cost_per_mile.arr[i];
    //fare->arr[i]=t+d;
}
return fare[len];
}

when I run this code I'm getting return value as " " or undefined and segmentation fault

Upvotes: 0

Views: 87

Answers (1)

Armali
Armali

Reputation: 19395

You failed to read and follow the comments you posted before the code. The length of the input array is not

len=sizeof(cost_per_minute.arr)/sizeof(float);

but rather

    len = cost_per_minute.size;

and you have to allocate the output array not with

arr_float fare[len];

but rather with

    arr_float fare = alloc_arr_float(len);

Consequently, the elements of fare are accessed not with

    fare->arr[i]

but rather with

        fare.arr[i]

Finally you have to return fare;.

Upvotes: 1

Related Questions