Witam wszystkich serdecznie.
Przerabiam aktualnie wskaźniki, a dokładniej przekazywanie wskaźników do funkcji oraz zwracanie przez funkcję wskaźnika i mam pewien problem związany ze zrozumieniem działania, a oto kod:
#include <iostream>
#include <stdlib.h>
using namespace std;
int* test_no_malloc(int* x, int* y);
int* test_malloc(int*x, int* y);
int main()
{
int a=1, b=3;
int* ptr_no_malloc = test_no_malloc(&a, &b);
cout << "test1 bez malloca!" << endl << "WARTOSC: " << *ptr_no_malloc << endl << "ADRES: " << &ptr_no_malloc << endl << endl;
cout << "test2 bez malloca!" << endl << "WARTOSC: " << *ptr_no_malloc << endl << "ADRES: " << &ptr_no_malloc << endl << endl;
cout << "test3 bez malloca!" << endl << "WARTOSC: " << *ptr_no_malloc << endl << "ADRES: " << &ptr_no_malloc << endl << endl;
int* ptr_malloc = test_malloc(&a, &b);
cout << "test1 bez malloca!" << endl << "WARTOSC: " << *ptr_malloc << endl << "ADRES: " << &ptr_malloc << endl << endl;
cout << "test2 bez malloca!" << endl << "WARTOSC: " << *ptr_malloc << endl << "ADRES: " << &ptr_malloc << endl << endl;
cout << "test3 bez malloca!" << endl << "WARTOSC: " << *ptr_malloc << endl << "ADRES: " << &ptr_malloc << endl << endl;
free(ptr_malloc);
return 0;
}
int* test_no_malloc(int* x, int* y)
{
int no_malloc = (*x) + (*y);
return &no_malloc;
}
int* test_malloc(int *x, int *y)
{
int* ptr_malloc = (int*)malloc(sizeof(int));
*ptr_malloc = (*x) + (*y);
return ptr_malloc;
}
Pytanie brzmi:
- Dlaczego jeśli zwracam wskaźnik bez użycia malloca, to po wyjsciu z funkcji tylko pierwsze wywolanie podaje prawidłową wartość, mimo iż adresy są identyczne(domyślam się, że wartości już nie ma pod adresem wskaźnika, ale dlaczego?), natomiast gdy używamy malloca, problemu nie ma.
- Czy jest jakiś sposób aby było poprawnie bez użycia malloca?
Prosze o wyrozumiałośc, gdyż jestem podczas nauki o wskaźnikach.
Pozdrawiam :)