Garbage value coming using arrays in C -


    #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 above code want pass 2 arrays function , it's size , want calculate product of 2 arrays using functions , pointers.in test case take 3 size of array , enter elements. product array shows result 1st 2 elements correctly not 3rd/ on debugging , including printf statements answer correctly. ( have commented in code)

how possible ? how come 2 printf statements able remove junk value ?

 int z[100]; 

is local function calculateproduct no longer available after return.

also return int array return type float *.

it should

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

you need dynamically allocate array in function int *calculateproduct(...).

like

int *z; z=(int *) malloc(100*sizeof(int)); 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -