Download presentation
Presentation is loading. Please wait.
Published byDoreen Mosley Modified over 8 years ago
1
Arrays, Strings, and Memory
2
Command Line Arguments #include 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 for return(0); } // End main
3
Example Input and Output Arg# Contents 1 a.exe 2 Apple 3 5 4 Cat 5 26.3 6 Eagle 7 -0.41 8 g H:\>a.exe Apple 5 Cat 26.3 Eagle -0.41 g
4
argv Array Contents argc argv 100: 102: 8 160 166 172 174 178 183 189 195 a.exe\0 Apple\0 5\0 Cat\0 26.3\0 Eagle\0 -0.41\0 g\0
5
Memory Contents 08016001660172017401 78018301890195000000 00000000000000000000 a.exe\0Apple 5 Cat 26.3 Eagle -0.41 g 000 100: 120: 140: 160: 180: 200: 220: 240: 260: 280: 300: 320: 00000000000000000000
6
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
7
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 variable printf("%d %d %d\n", &sum, &(valuesTable[20]), &cost); printf("Cost figure: %d\n", cost); printf("Sum figure: %d\n", sum); } // End main
8
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
9
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
10
Dynamic Memory Allocation using calloc 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 for return(0); } // End initializeAdjacentStatesList Example
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.