Answer the question
In order to leave comments, you need to log in
Why are the values changing?
C code.
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int * getMas(int n){
int mas[n];
int i;
for(i = 0; i < n; i++)
{
mas[i] = rand() % 100;
}
int *ptr = mas;
return ptr;
}
void main()
{
srand(time(NULL));
int n = 10;
int * ptr = getMas(n);
printf("first %d %d %d %d ", ptr[0], ptr[1], ptr[3], ptr[4]);
printf("\n");
printf("second %d %d %d %d ", ptr[0], ptr[1], ptr[3], ptr[4]);
}
// first 14 63 38 39
// second 1 32762 32762 1
Answer the question
In order to leave comments, you need to log in
Because an array cannot be returned from a function. Right now you're just returning a pointer. While the pointer is in the getMas function, it actually points to an array. As soon as you left getMas the stack collapsed (your array is on the stack) and the memory where the array used to be is no longer valid.
After calling the first printf, the same memory on the stack that your array once occupied was allocated for the needs of printf, and printf filled this memory with something of its own, so in the third printf you have garbage.
Your program does not crash with an error, because memory is always allocated on the stack. "Stack collapse" is simply increment/decrement of the stack pointer register.
You have 2 options.
1. Simple - allocate an array in main, pass it to getMas. From getMas you can already return nothing, just fill in the array there.
2. Allocate a dynamic array in getMas using malloc. In main, don't forget to free the memory allocated for the array. This is a bad option, because memory is allocated at one program level and freed at another. But in your simple task, you can ignore this for now.
You are returning a dangling pointer, hence the undefined behavior
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question