Created
March 11, 2013 19:07
-
-
Save ereidland/5136797 to your computer and use it in GitHub Desktop.
Example 2 at Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
#define ARRAY_SIZE 128 | |
void lol(const int); //Function header for lol. | |
int main() | |
{ | |
char staticArray[ARRAY_SIZE]; //Static. Generated on main initialization. Memory managed by progam. | |
//Char * is a pointer to a character. | |
char * dynamicArray = new char[ARRAY_SIZE]; //New [size] returns a pointer to the address of the first value. | |
strcpy(staticArray, "Hello!"); //String copy arguments: (destination, source). | |
//Strcpy goes based on the strlen of the the source. | |
//Strlen determines the length of the string by finding the first character that is set to 0. Not the character '0', but the value 0. | |
cout << staticArray << endl; //Print static array. | |
strcpy(dynamicArray, "Things"); //Copy from "Things" to dynamicArray. | |
cout << "Length of dynamicArray: " << strlen(dynamicArray) << endl; //Strlen returns an int and takes a const char * as the argument. | |
cout << dynamicArray << endl; //Print dynamic array. | |
cout << dynamicArray[2] << endl; //Print dynamic array at 2. | |
//The [] operator is the same as: | |
//*(pointer + index); | |
cout << *(dynamicArray + 2) << endl; //Print the character at an offset of 2. Note the de-reference. | |
strcpy(dynamicArray + strlen(dynamicArray), " and more."); //Equal to strcat(dynamicArray, "and more."); | |
cout << dynamicArray << endl; //Print it. | |
//Always clean up dynamic arrays when you're done with them. Otherwise the world will end. | |
delete [] dynamicArray; //Note the [] on delete. It let compiler know that it's deleting an array. | |
//staticArray is automatically cleaned up by the program. | |
int notconst = 0; //Always make sure to set variables before using them. | |
//Example of passing something to lol (function): | |
lol(notconst); //Argument does not have to be a constant. | |
//Const just means that, from the perspective of the function, it is constant. | |
notconst = 1; //Still not constant. | |
return 0; //Result to be sent back to the OS once this is complete. | |
} | |
void lol(const int notlol) | |
{ | |
//Can't change notlol here. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment