#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?