I'm trying to write a program that calls upon a function that creates an array with random numbers and then sort them. When thats done I want to return a pointer to the array to the main function. I then want to print the array. And everything works fine if I just print one value in the array. However if I print more than one value I get some other value. Here is the main function:
int * createArr(){
int arrLenth = 100;
int arr[arrLenth];
int i, j, temp, pos = 0;
/*ASSIGNING ARRAY VALUES */
for(i=0;i<arrLenth; i++){
arr[i] = rand() % 900;
}
/* SORTING ARRAY */
for(i = 0; i < arrLenth; i++){
for(j = 0; j < arrLenth; j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
/* PRINTING ARRAY*/
for(i=0;i<arrLenth; i++){
printf("%d, ", arr[i]);
}
int *parr = arr;
//printf("\n%p", parr);
return parr;
}
int main() {
int *p = createArr(); //pointer to the array
printf("\n%d", *(p+1));
printf("\n%d", *(p+1));
return 0;
}
This gives me the output:
45 (which is correct)
1771768448 (which is not correct)
What is causing this? I'm printing the exact same line twice but get difrent outputs. Also tell me if you need to see the function where i create the array, I don't feel like it's needed because everything works fine there.