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?

1

2 Answers 2

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)); 
Sign up to request clarification or add additional context in comments.

1 Comment

Dealing with numerical arrays, it is often useful to allocate with calloc to insure all values are zeroed. z=calloc(100, sizeof(int));
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.