0
#include <stdio.h>
int i;
float *calculateProduct(int *,int *,int );
int main()
{

        int n;
        
        printf("Enter length of array\n");
        scanf("%d",&n);
        
        int x[100];
        int y[100];
        for(i=0;i<n;i++)
        {
            scanf("%d",&x[i]);
        }
        for(i=0;i<n;i++)
        {
            scanf("%d",&y[i]);
        }
        
        /*for(i=0;i<n;i++)
        {
            printf("%d ",x[i]);
        }
        printf("\n");
        for(i=0;i<n;i++)
        {
            printf("%d ",y[i]);
        }
        printf("\n");
        */
        int *ptr;
        ptr=calculateProduct( x, y, n);
        for(i=0;i<n;i++)
        printf("%d ",*(ptr+i));
    
        return 0;
}

float *calculateProduct(int *x,int *y,int n)
{
    int z[100];
    for(i=0;i<n;i++)
    {
        z[i]=x[i]*y[i]; 
    }
    
    return z;
}

In the code above, I want to pass 2 arrays to a function and its size and then want to calculate the product of those 2 arrays all using functions and pointers.

In my test case, I take 3 as the size of the array and enter the elements. The product array shows the result for 1st two elements correctly but not for the 3rd. However, on debugging and including some printf statements I get my answer correctly (I have commented that in my code).

How is that possible? How come 2 printf statements are able to remove the junk value?

Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
mr-karan
  • 203
  • 4
  • 11
  • http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris Jun 26 '14 at 05:01

2 Answers2

3
 int z[100];

is local to function calculateProduct so it will no longer available after return.

Also you return int array but your return type is float *.

It should be

int *calculateProduct(int *x,int *y,int n)

you need to dynamically allocate the array in function int *calculateProduct(...).

Like

int *z;
z=(int *) malloc(100*sizeof(int));
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • 1
    Dealing with numerical arrays, it is often useful to allocate with `calloc` to insure all values are zeroed. `z=calloc(100, sizeof(int));` – David C. Rankin Jun 26 '14 at 05:47
1

You should check the return value from scanf to ensure that the arrays x and y are actually getting populated.

Also either create the array z dynamically or pass it into the function. Besides why are you returning a float *?

The best option in my opinio is

void calculateProduct(int *x,int *y, int *z, int n)
{
    for(i=0;i<n;i++)
    {
        z[i]=x[i]*y[i]; 
    }
}

With z being defined in the similar manner to x

Ed Heal
  • 59,252
  • 17
  • 87
  • 127