100 likes | 212 Views
Arrays, Strings, and Memory. Command Line Arguments. #include <stdio.h> int main( int argc, char *argv[]) { int i; printf( "Arg# Contents<br>" ); for (i = 0; i < argc; i++) { printf( "%2d %s<br>" , (i+1), argv[i]); } // End for return (0); } // End main.
E N D
Command Line Arguments #include<stdio.h>int main(int argc, char *argv[]){int i; printf("Arg# Contents\n");for (i = 0; i < argc; i++) { printf("%2d %s\n", (i+1), argv[i]); } // End forreturn(0);} // End main
Example Input and Output H:\>a.exe Apple 5 Cat 26.3 Eagle -0.41 g Arg# Contents 1 a.exe 2 Apple 3 5 4 Cat 5 26.3 6 Eagle 7 -0.41 8 g
argv Array Contents argc 100: 8 argv 102: 160 a.exe\0 166 Apple\0 5\0 172 174 Cat\0 178 26.3\0 183 Eagle\0 189 -0.41\0 195 g\0
Memory Contents 100: 0 8 0 1 6 0 0 1 6 6 0 1 7 2 0 1 7 4 0 1 120: 7 8 0 1 8 3 0 1 8 9 0 1 9 5 0 0 0 0 0 0 140: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 160: a . e x e \0 A p p l e \0 5 \0 C a t \0 2 6 180: . 3 \0 E a g l e \0 - 0 . 4 1 \0 g \0 0 0 0 200: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 220: 240: 260: 280: 300: 320:
Pointer Arithmetic int main(int argc, char *argv[]){int i;char *programName;char *argNameA;char *argNameB; programName = argv[0];argNameA = argv[1];argNameB = *(argv + 1);printf("%s %s %s\n", programName, argNameA, argNameB);argNameA = argv[4];argNameB = *(argv + 4);printf("\n%s %s\n", argNameA, argNameB); return(0);} // End main
Importance of Range Checking int main(void){int sum = 50;int valuesTable[5] = {3, 6, 9, 12, 15};int cost = 100;valuesTable[0] = 13;*(valuesTable + 0) = 13;*(valuesTable + 2) = 19;valuesTable[-1] = 36; // Puts 36 in the sum variable*(valuesTable - 1) = 36; // Also puts 36 in the sum variableprintf("%d %d %d\n", &sum, &(valuesTable[20]), &cost);printf("Cost figure: %d\n", cost);printf("Sum figure: %d\n", sum);} // End main
Dynamic Memory Allocation • malloc() – allocates a data object and returns a pointer to it • calloc() – allocates an array data object and returns a pointer to it • free() – deallocates the data object whose address is the pointer • sizeof – returns the size in bytes of a data object
Dynamic Memory Allocation using malloc int main(void){int a = 27;float b = 789.56;int *xPtr;float *yPtr;xPtr = (int *) malloc( sizeof(int) );*xPtr = a;yPtr = (float *) malloc( sizeof(float) );*yPtr = b;printf("%d %.2f\n", a, b);printf("%d %.2f\n", *xPtr, *yPtr);free(xPtr);free(yPtr);return(0);} // End main
Dynamic Memory Allocation using calloc Example int initializeAdjacentStatesList(char *adjacentList[]){int i;for (i = 0; i < MAX_ADJACENT_STATES; i++) {// Allocate memory for each character string element// of the adjacentList adjacentList[i] = calloc(STATE_CODE_LENGTH, sizeof(char)); strcpy(adjacentList[i], ZZ_STATE); } // End forreturn(0);} // End initializeAdjacentStatesList