To run a C++ program:
myprogram.cpp
)cd
command to get to the folder where your C++ files areg++ myprogram.cpp
to compile. If there are error messages, correct the mistake and compile again (note: an old executable a.out
will still be there until it is overwritten by a new one. If your program failed to compile and you still try to run it, you would be running the old version).a.out
on the command line. If you get file not found
error, use ./a.out
instead.The example of using dynamic memory allocation
#include
#include // need this to use malloc
using namespace std;
int main () {
int n, i;
int * numbers;
cout << "Please enter a number: ";
cin >> n;
// allocate memory for n integers:
numbers = (int *) malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
numbers[i] = i;
}
for (i = 0; i < n; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
// free the memory at the end
free(numbers);
}