I am making this program in which my main function calls a function which returns an array after the calculation. I checked already that calculation is right inside the local function. But when I return that array to 'main' function then I only can print the correct value one time and it prints wrong value all other times.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int* getJoinedPipes(int input1_size, int* input1,int* output_size){
int i,j,temp;
int op1[input1_size-1];
*output_size = input1_size - 1;
for(i=0; i<input1_size; i++){
for(j=i+1; j<input1_size; j++){
if(input1[i] > input1[j]){
temp = input1[i];
input1[i] = input1[j];
input1[j] = temp;
}
}
}
op1[0]=input1[0] + input1[1];
for(i=1;i<input1_size-1;i++){
op1[i] = op1[i-1]+input1[i+1];
}
//printf("%d\n",op1[2]);
return op1;
}
int main() {
int output_size;
int* output;
int ip1_size = 0;
int ip1_i;
scanf("%d\n", &ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
int ip1_item;
scanf("%d", &ip1_item);
ip1[ip1_i] = ip1_item;
}
output = getJoinedPipes(ip1_size,ip1,&output_size);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
printf("a==%d\n",output[0]);
int output_i;
for(output_i=0; output_i < output_size; output_i++) {
printf("%d\n", output[output_i]);
}
return 0;
}
Output should be
5
9
15
But in the console, it's showing the following (after dry run).
a==5
a==1943372821
a==1943372821
1943372821
17
6356632
You can see first time its giving correct value (5) and later for same print its giving garbage values.