1

I need help with array return using pointer. Please see the codes below. Code 1 works fine but Code 2 gives me wrong output.

Code 1 :-

#include <stdio.h>
#include <stdint.h>

float *arrayproduct(float *passedarray);

int main(void)
{
    float array[] = {2,4,6,8.5};
    float *result;
    
    result = arrayproduct(array);

    printf("Elements of modified array are %f\n%f\n%f\n%f\n", result[0],result[1],result[2],result[3]);
    
    return 0;
}

float *arrayproduct(float *passedarray)
{
    int i;
    float product[4]={};
    float *ptr;
    ptr = product;
    
    for(i=0;i<4;i++)
    {
        ptr[i] = passedarray[i] - 1;
    }
    
    return ptr;
}

The output of Code 1 is :- Elements of modified array are

1.000000

3.000000

5.000000

7.500000

Code 2 :-

#include <stdio.h>
#include <stdint.h>

float *arrayproduct(float *passedarray);

int main(void)
{
    float array[] = {2,4,6,8.5};
    float *result;
    int i;

    result = arrayproduct(array);

    for(i=0;i<4;i++)
    {
        printf("%f\n",result[i]);
    }

    return 0;
}

float *arrayproduct(float *passedarray)
{
    int i;
    float product[4]={};
    float *ptr;
    ptr = product;
    
    for(i=0;i<4;i++)
    {
        ptr[i] = passedarray[i] - 1;
    }
    
    return ptr;
}

The output of Code 2 is :- 1.000000

-40110188476235776.000000

138619665717382032373921611776.000000

0.000000

Can someone please explain the issue here? Where am I making a mistake?

Thanks

Paddy
  • 11
  • 1
  • 5
    You can't return a pointer to a *local* array. Note that both codes are invalid. This array is ceasing to exist once the function finishes. Where is that duplicate now... – Eugene Sh. Jun 08 '21 at 15:09
  • Thanks @EugeneSh. for pointing my mistake. With some other suggestions that mentioned to use malloc for allocating memory, I was able to solve my issue. But I still don't understand how my "Code 1" worked. Can you please brief me on that? – Paddy Jun 08 '21 at 15:25
  • This is undefined behavior, which might make the program to "pretend" to be working. Accidentally the memory that was allocated for the array was not cleared or reused at the time of the output, so the values were printed as you expected. – Eugene Sh. Jun 08 '21 at 15:28
  • Thanks. That makes sense. – Paddy Jun 08 '21 at 15:31

0 Answers0