Pointers and memory (arrays)

Learning a programming language is hard enough without having to wrangle your computer into compiling and executing your code. From beginners to experts, the tips here will make life in C++ easier.
Post Reply
darknkreepy3#
Site Admin
Posts: 254
Joined: Tue Oct 27, 2009 9:33 pm

Pointers and memory (arrays)

Post by darknkreepy3# »

Code: Select all

/*
pointers in c++ by Kristoffe Brodeur
06-04-2010
*/
#include <iostream>

using namespace std;

int main()
{
    int numberArr[4]={1,3,7,11};
    //
    for(int a=0;a<4;a++)
         {
         cout << "element[" << a << "](" << numberArr[a] << ")\n";
         }
    
    int *pointerEle=&numberArr[2];
    cout << "numberArr element [2] is (" << *pointerEle << ")" << endl;
    cout << "to point to the next array element, add 1 to the pointer [2+1](" << *(pointerEle+1) << ")" << endl;
    cout << "if parenthesis aren't used *(pointerEle+1) but *pointerEle+1 is\n";
    cout << "You get he VALUE of *pointerEle's location +1, which is (" << *pointerEle << ")+1=" << *pointerEle+1 << endl;
    cout << "------------------\n";
    //-----dynamic arrays, finding free memoryand allocating it for use
    //make a pointer, type integer and zero it out
    int *newMemoryArr=0;
    //with that pointer make a new array of 100 possible integers and allocate memory for it
    newMemoryArr=new int[100];
    int varTest=newMemoryArr[5];
    varTest=216;
    cout << "after making a new array of integers, we can then define them\n"
         << "by using a variable pointing to the memory location\n"
         << "the variable varTest=" << varTest << "\n"
         << "and the array newMemoryArr is a series of pointers to memory. \n"
         << "newMemoryArr[5]=" << newMemoryArr << "\n";
    //-----expanding an array:if we need 166 positions but only hae 100 in newMemoryArr, we should make a larger array
    int largerAmt=166;
    //make a pointer, type integer and zero it out
    int *newLargerArr=0;
    newLargerArr=new int[largerAmt];
    //
    for(int x=0;x<100;x++)
         {
          newLargerArr[x]=newMmoryArr[x];
         }
    //c++ can mass readjust all pointers in the old array to point to the new array of 0-99(100)
    newMemoryArr=newLargerArr;
    //-----delete the array if no longer needed, to free up memory for something else
    //delete [all cases 0~inf] of array newMemoryArr;
    delete [] newMemoryArr;
    delete [] newLargerArr;
    system("PAUSE");
    return EXIT_SUCCESS;
}
Post Reply