12.07.2015 Views

CSCI 102

CSCI 102

CSCI 102

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

DYNAMIC MEMORY &COMMAND LINE ARGUMENTS© Copyright 2013 Brent Nash & Mark Redekopp, All Rights Reserved5


Un Solo MensajeEl verdadero Dios, el CreadorEnvió a:Para comunicar que:-------Adán-------Noé-------Abraham-------Moisés-------Jesús-------MuhammadDios es UnoDios es unoDios es UnoDios es UnoDios es UnoDios es Uno6


Arrays of pointers‣ We can have arraysof pointers just like wehave arrays of otherdata types‣ Usually each value ofthe array is a pointerto a collection of“related” data– Could be to anotherarraychar *names[4] ={“Bill”,“Suzy”,“Pedro”,“Ann”};int main(int argc, char *argv[]){int i;}for(i=0; i < 4; i++){cout


Command Line Arguments‣ Now we can understand the argumentspassed to the main function (int argc,char *argv[])‣ At the command prompt we can giveinputs to our program rather thanmaking querying the user interactively:– $ ./prog1 4 0.5 100000– $ cp broke.c broke2.c‣ Command line string is broken atwhitespaces and copied into individualstrings and then packaged into an array(argv)– Each entry is a pointer to a string (char *)‣ Argc indicates how long that arrays is(argv[0] is always the executable name)© Copyright 2013 Brent Nash & Mark Redekopp, All Rights ReservedCommand line:p r o g 1 4 0 . 5 1 0 0 0 0 0argv[0]argv[1]argv[2]argv[3]Linux shell command line./prog1 Executableint main(int argc, char *argv[])argc = 4 argv = 5a05a0240288300196240p r o g 1 \02884 \03000 . 5 \01961 0 0 0 0 0 \09


Command Line Arguments‣ Recommended usage:– Upon startup check argc to make surethe user has input the desired numberof args (remember the executablecounts as one of the args.)‣ Problem:– Each argument is a textstring…for numbers we want itsnumeric representation not itsASCII representation– cstdlib defines:atoi() [ASCII to Integer] andatof() [ASCII to float/double]– Each of these functions expects apointer to the string to convertargv[0]argv[1]argv[2]argv[3]#include #include using namespace std;p r o g 1 \04 \00 . 5 \01 0 0 0 0 0 \0// char **argv is the same as char *argv[]int main(int argc, char **argv){int init, num_sims;double p;if(argc < 4){cout


Exercise‣ Write a program that– Defines a function that accepts an integer, N as input and thengenerates an array of N random integers and returns it to the caller– From main ask the user for N, call your function and "store" thereturn result– Iterate over the array returned by your function and average thevalues.– Print that average…is that value close to _______________(expected value)?© Copyright 2013 Brent Nash & Mark Redekopp, All Rights Reserved11

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!