-3

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!

  • Change the function signature to `void createLine(int* &p_line, int size);` you are operating on a value copy inside that function. – user0042 Aug 05 '17 at 16:49
  • 1
    Your question is the same as: I have `void foo(int a) { a = 5; };`. Why is `b` always `10` even after I call `foo`? `int b = 10; foo(b); // b is still 10`. – Rakete1111 Aug 05 '17 at 16:50
  • 1
    Learn std::vector first. –  Aug 05 '17 at 16:53

1 Answers1

1

Parameters in C/C++ are passed by value. Thus your changes to p_line in createLine() are discarded.

You could return the new value, or use a reference (int *&p_line) or use a double pointer (int **p_line).

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207