pointers explained ?

Started by
11 comments, last by obi-wan shinobi 18 years, 10 months ago
That Binky video was a decent beginner lesson on pointers, even though the most enjoyable part for me was when he got zapped into pieces (lol).

Anyway, one use of pointers is to dynamically allocate space for an array:

void main() {int num = 1;cout << "How many elements: ";    cin >> num;                       if(num < 1) {  cout << "It must be above 0!";    return;                         //end program immediately  }int array[num];                   //causes about 3 errors in C++int *array = new int[num];        //works - an array size determined at runtimeif(array==NULL) {  cout << "Memory unavailable!";  return;  }for(int i=0;i<num;i++)            //for every element in the array...  cin >> array;                //...assign it the value you want it to havedelete array;                     //frees memory, only call once per pointerdelete array;                     //this second call may crash your program }
Advertisement
Quote:Original post by obi-wan shinobi

Anyway, one use of pointers is to dynamically allocate space for an array:



Only if you're feeling particularly masochistic, or using plain C, yet I repeat myself.

[appolgies to Mark Twain.]

Quote:Original post by Telastyn
Quote:Original post by obi-wan shinobi

Anyway, one use of pointers is to dynamically allocate space for an array:



Only if you're feeling particularly masochistic, or using plain C, yet I repeat myself.

[appolgies to Mark Twain.]


At the very least, it'll have to do until I master vectors... :)

This topic is closed to new replies.

Advertisement