I'm new to C++ and just learning about pointers, and tried to create a simple number line program using pointers and arrays (I know I can do this in a simpler way, but it's just for practice). However, when I try to run my code, it freezes when it tries to allocate the array.
#include<iostream>
using namespace std;
void createLine(int* p_line, int size);
void printLine(int* p_line, int size);
int main(){
int* p_line = NULL;
int size = 0;
cout << "Enter the size of the number line: ";
cin >> size;
createLine(p_line, size);
printLine(p_line, size); //It doesn't work when printLine is here
delete[] p_line;
}
void createLine(int* p_line, int size){
cout << "Size of the number line: " << size << "." << endl;
p_line = new int[size];
for(int i = 0; i < size; i++){
p_line[i] = i + 1;
}
//If printLine is here, it works
}
void printLine(int* p_line, int size){
cout << "Printing line: ";
for(int i = 0; i < size; i++){
cout << p_line[i] << " , ";
}
}
The weird thing is, if I move the printLine call to the end of createLine, the program runs perfectly fine. I've tried looking on the internet, but everything I find seems to suggest that this should run fine.
The only explanation that I can think of is that the program tries to run printLine before createLine is done running, so it tries to access p_line when it's still NULL. But if I understand C++ correctly, this shouldn't happen, right?
Any explanation would be greatly appreciated, thanks!