Allocating normal variables (int ?) ?
Hi, I getting familiar with allocating, but all I have been allocating is arrays
1 2 3 4 5 6 7
|
int numberstocount, numbers[1];
int* p_numbers = numbers;
cout << "enter number to be counted : ";
cin >> numberstocount;
p_numbers = new int[numberstocount];
|
I have tried allocating normal variables (variables that hold simple numbers).
But I have been getting same results.
I use this is the code :
1 2 3 4 5 6 7 8
|
int x = 20;
int* p = &x;
cout << x << endl;
p = new int[100];
cout << x;
|
can I allocate normal variables ? I know I can, but how ? am I doing something wrong ?
Allocating arrays:
1 2 3 4 5 6 7 8
|
int count;
std::cout << "How lagrge should array be?\n";
std::cin >> count;
int* array = new int[count];
//Somewhere later
delete[] array;
|
Allocating single variable:
1 2 3 4
|
int* var = new int;
//Somewhere later
delete var;
|
still getting same result. can you make a simple program that work ? like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int main()
{
int x = 20;
int* p = &x;
cout << x << endl;
p = new int;
cout << x;
cin.ignore();
cin.get();
return 0;
}
|
^this don't work,
Last edited on
It work. Exactly like it should. What your problem with it?
If you want another behavior, tell and I will show you.
BTW, whay do you need line 3? You do not access x through p, why are you assigning its address to p?
If you want to change values through pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main()
{
int x = 20;
std::cout << " x = " << x << '\n';
int* p = &x;
*p = 10;
std::cout << " x = " << x << '\n';
std::cout << "*p = " << *p << '\n';
p = new int;
*p = -100;
std::cout << " x = " << x << '\n';
std::cout << "*p = " << *p << '\n';
*p = 25;
std::cout << " x = " << x << '\n';
std::cout << "*p = " << *p << '\n';
delete p; //NEVER forget to delete allocated memory
std::cin.ignore();
std::cin.get();
}
|
x = 20
x = 10
*p = 10
x = 10
*p = -100
x = 10
*p = 25 |
http://ideone.com/dPHVI5
Topic archived. No new replies allowed.