Memory. Memory Topics. Passing by Value. Passing by Reference. Dynamic Memory Allocation. Passing a Pointer to a Pointer. Related Memory Functions

Size: px
Start display at page:

Download "Memory. Memory Topics. Passing by Value. Passing by Reference. Dynamic Memory Allocation. Passing a Pointer to a Pointer. Related Memory Functions"

Transcription

1 Memory Memory Memory Topics Passing by Value Passing by Reference Dynamic Memory Allocation Passing a Pointer to a Pointer Related Memory Functions Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/040Memory/110Memory.html [3/29/2008 9:57:45 AM]

2 Memory Memory Passing by Value A copy of the value is passed. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...20Work/AdvancedC/Binders/040Memory/120PassByValue.html [3/29/2008 9:57:45 AM]

3 Memory Memory Passing by Reference A pointer to the value is passed. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/040Memory/130PassByReference.html [3/29/2008 9:57:45 AM]

4 Memory Memory Dynamic Memory Allocation void *malloc( size_t size ); Allocates size bytes of memory on the heap. Memory must be released by calling free. MIGHT return NULL if size equals 0. Returns NULL on failure. void *calloc( size_t count, size_t size ); Allocates size * count bytes of memory on the heap. Convenient for allocating arrays. Memory initialized to binary 0. Memory must be released by calling free. MIGHT return NULL if size or count equal 0. Returns NULL on failure. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/040Memory/140malloc.html [3/29/2008 9:57:45 AM]

5 Memory Memory Dynamic Memory Allocation void *realloc( void *old_ptr, size_t size ); Resizes (to size) memory indicated by old_ptr. If old_ptr equals 0 works like malloc. If size equals 0 old_ptr is freed and NULL is returned. Memory must be released (usually by calling free). MIGHT return a pointer to a new area. MIGHT return NULL if size or count equal 0. Returns NULL on failure. void free( void *ptr ); Frees the (previously allocated) memory indicated by ptr. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/040Memory/150realloc.html [3/29/2008 9:57:46 AM]

6 Memory Memory Common Errors Forgetting to check for allocation failure. Reading from initialized memory. Forgetting to free memory. Freeing the same block of memory more than once. Reading/writing beyond the end of a memory block. Assumptions about zero-initialization, e.g.: A pointer initialized to binary 0 may be invalid. A floating point variable initialized to binary 0 may not be a valid number. Reallocating a position-dependent structure. Fragmenting memory (this is a concern, not really an error). Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...0Work/AdvancedC/Binders/040Memory/160CommonErrors.html [3/29/2008 9:57:46 AM]

7 Memory Memory Position Dependence (continued...) Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My%.../AdvancedC/Binders/040Memory/170PositionDependence.html [3/29/2008 9:57:46 AM]

8 Memory Memory Position Dependence (continued) Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My%.../AdvancedC/Binders/040Memory/180PositionDependence.html [3/29/2008 9:57:46 AM]

9 Memory Memory Passing a Pointer-to-Pointer Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/040Memory/190PointerToPointer.html [3/29/2008 9:57:47 AM]

10 Memory Memory Related Memory Functions int memcmp( const void *ptr1, const void *ptr2, size_t len ); Compares the first len bytes in two blocks of memory; similar to strcmp. void *memcpy( void *dst, const void *src, size_t len ); Copies len bytes from src to dst. Returns dst. May not be safe if src and dst overlap. void *memmove( void *dst, const void *src, size_t len ); Copies len bytes from src to dst. Returns dst. Guaranteed safe if src and dst overlap. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...School%20Work/AdvancedC/Binders/040Memory/200Misc.html [3/29/2008 9:57:47 AM]

11 Memory Memory Memory Management Tools A variety of tools are available to assist in detecting and isolating memory leaks and similar problems, such as memory overruns, reading from uninitialized memory and freeing memory that has never been allocated; see the Linux Journal Article. Valgrind Rational Purify SmartHeap HeapAgent BoundsChecker Visual C++ (look for _CrtMemCheckpoint in your index) Dmalloc ccmalloc NJAMD YAMD mpatrol Insure++ See also Balancing a Binary Tree: Checking for Memory Leaks. Memory file:///c /Documents%20and%20Settings/Jack%20Straub/My...chool%20Work/AdvancedC/Binders/040Memory/210Tools.html [3/29/2008 9:57:47 AM]

12 Arrays and Pointers Arrays and Pointers Arrays and Pointers Topics Conversion to Pointer Array of Arrays Array of Pointers Multidimensional Arrays Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...C/Binders/050ArraysAndPointers/110ArraysAndPointers.html [3/29/2008 9:57:47 AM]

13 Arrays and Pointers Arrays and Pointers Conversion to Pointer An array identifier is converted to a pointer to the array's first element: When the identifier is used as an argument to a function; When the identifier is used in an expression. Exception: When an array identifier is used as the argument of the sizeof operator no conversion takes place; the result is the size of the entire array. static void funk( int *farg /* Could also use int farg[] */ ); int main( int argc, char **argv ) int arr[10] = 10, 20, 30, 40, 50 ; int *parr = arr; printf( "sizeof(arr) = %u, sizeof(parr) = %u\n", sizeof(arr), sizeof(parr) ); funk( arr ); return EXIT_SUCCESS; static void funk( int *farg ) printf( "sizeof(farg) = %u, *farg = %d\n", sizeof(farg), *farg ); sizeof(arr) = 40, sizeof(parr) = 4 sizeof(farg) = 4, *farg = 10 Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...Binders/050ArraysAndPointers/120ConversionToPointer.html [3/29/2008 9:57:48 AM]

14 Arrays and Pointers Arrays and Pointers Conversion to Pointer Given an array of some type: type arr[n]; the expression arr[inx] is converted to: *(arr + inx) Example: int main( int argc, char **argv ) int arr[10] = 10, 20, 30, 40, 50 ; printf( "arr[3] = %d, 3[arr] = %d\n", arr[3], 3[arr] ); return EXIT_SUCCESS; arr[3] = 40, 3[arr] = 40 Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...Binders/050ArraysAndPointers/130ConversionToPointer.html [3/29/2008 9:57:48 AM]

15 Arrays and Pointers Arrays and Pointers Array of Arrays Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...ncedC/Binders/050ArraysAndPointers/140ArrayOfArrays.html [3/29/2008 9:57:48 AM]

16 Arrays and Pointers Arrays and Pointers Array of Pointers continued... Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...edC/Binders/050ArraysAndPointers/150ArrayOfPointers.html [3/29/2008 9:57:48 AM]

17 Arrays and Pointers Arrays and Pointers Array of Pointers (continued) int main( int argc, char **argv ) char *carrp[2] = "big", "pony" ; int iarr1[4] = -1, -2, -3, -4 ; int iarr2[5] = 1, 2, 3, 4, 5 ; int *iarrp[2] = iarr1, iarr2 ; printf( "%s, %s\n", carrp[0], carrp[1] ); printf( "%d, %d\n", iarrp[0][0], iarrp[1][0] ); printf( "%d, %d\n", iarrp[0][3], iarrp[1][4] ); return EXIT_SUCCESS; big, pony -1, 1-4, 5 Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...edC/Binders/050ArraysAndPointers/160ArrayOfPointers.html [3/29/2008 9:57:49 AM]

18 Arrays and Pointers Arrays and Pointers Multidimensional Arrays Arrays in C are row-major: The outermost index varies most quickly; Elements associated with the outermost index are stored in memory first; When a function parameter is declared as a multidimensional array you must declare the extent of each dimension except the first. static void funk( int arr[][5][7], int count ); int main( int argc, char **argv ) int iarr[3][5][7]; funk( iarr, 3 ); return EXIT_SUCCESS; static void funk( int arr[][5][7], int count ) int inx = 0; int jnx = 0; int knx = 0; int xxx = 0; /* To process an array most efficiently and avoid * unnecessary memory swapping, access the array in * order; that is, vary the rightmost index fastest. */ for ( inx = 0 ; inx < count ; ++inx ) for ( jnx = 0 ; jnx < 5 ; ++jnx ) for ( knx = 0 ; knx < 7 ; ++knx ) if ( xxx++ % 10 == 0 ) puts( "" ); printf( "%p ", &arr[inx][jnx][knx] ); 0x22cb30 0x22cb34 0x22cb38 0x22cb3c 0x22cb40 0x22cb44 0x22cb48 0x22cb4c 0x22cb50 0x22cb54 0x22cb58 0x22cb5c 0x22cb60 0x22cb64 0x22cb68 0x22cb6c 0x22cb70 0x22cb74 0x22cb78 0x22cb7c 0x22cb80 0x22cb84 0x22cb88 0x22cb8c 0x22cb90 0x22cb94 0x22cb98 0x22cb9c 0x22cba0 0x22cba4 0x22cba8 0x22cbac 0x22cbb0 0x22cbb4 0x22cbb8 0x22cbbc 0x22cbc0 0x22cbc4 0x22cbc8 0x22cbcc 0x22cbd0 0x22cbd4 0x22cbd8 0x22cbdc 0x22cbe0 0x22cbe4 0x22cbe8 0x22cbec 0x22cbf0 0x22cbf4 0x22cbf8 0x22cbfc 0x22cc00 0x22cc04 0x22cc08 0x22cc0c 0x22cc10 0x22cc14 0x22cc18 0x22cc1c 0x22cc20 0x22cc24 0x22cc28 0x22cc2c 0x22cc30 0x22cc34 0x22cc38 0x22cc3c 0x22cc40 0x22cc44 0x22cc48 0x22cc4c 0x22cc50 0x22cc54 0x22cc58 0x22cc5c 0x22cc60 0x22cc64 0x22cc68 0x22cc6c 0x22cc70 0x22cc74 0x22cc78 0x22cc7c 0x22cc80 0x22cc84 0x22cc88 0x22cc8c 0x22cc90 0x22cc94 0x22cc98 0x22cc9c 0x22cca0 0x22cca4 0x22cca8 0x22ccac 0x22ccb0 0x22ccb4 0x22ccb8 0x22ccbc 0x22ccc0 0x22ccc4 0x22ccc8 0x22cccc 0x22ccd0 file:///c /Documents%20and%20Settings/Jack%20Straub/M...s/050ArraysAndPointers/170MultidimensionalArrays.html (1 of 2) [3/29/2008 9:57:49 AM]

19 Arrays and Pointers Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/M...s/050ArraysAndPointers/170MultidimensionalArrays.html (2 of 2) [3/29/2008 9:57:49 AM]

20 Arrays and Pointers Arrays and Pointers Multidimensional Arrays The subscript operator is left-to-right associative: arr[n0][n1][n2] ==> *(arr[n0][n1] + n2) ==> *(*(arr[n0] + n1) + n2) ==> *(*(*(arr + n0) + n1) + n2) Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...ders/050ArraysAndPointers/180MultidimensionalArrays.html [3/29/2008 9:57:49 AM]

21 Arrays and Pointers Arrays and Pointers Multidimensional Arrays Given an array: type arr[a0][a1][a2]; From the compiler's perspective, the address of element arr[n0][n1][n2] Is calculated using the formula: arr + (n0*a1*a2 + n1*a2 + n2) * sizeof(type) Note that the address is independent of A0. int main( int argc, char **argv ) int arr[3][5][7]; void *ptr = NULL; arr[1][2][4] = 17; ptr = (char *)arr + (1*5*7 + 2*7 + 4) * sizeof(int); printf( "%d, %d\n", arr[1][2][4], *(int *)ptr ); return EXIT_SUCCESS; Arrays and Pointers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...ders/050ArraysAndPointers/190MultidimensionalArrays.html [3/29/2008 9:57:50 AM]

22 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers Topics Storage Classes Type Specifiers Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...cedC/Binders/060ClassesAndTypes/110ClassesAndTypes.html [3/29/2008 9:57:50 AM]

23 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers Storage Classes auto extern register static typedef Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...ork/AdvancedC/Binders/060ClassesAndTypes/120Classes.html [3/29/2008 9:57:50 AM]

24 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers Automatic (auto) Storage Class Only variables declared within blocks may have this storage class. This is the default for variables declared within blocks, so the auto keyword is rarely seen. Storage for automatic variable is allocated every time the declaring block is entered. Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...0Work/AdvancedC/Binders/060ClassesAndTypes/130Auto.html [3/29/2008 9:57:50 AM]

25 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers External (extern) Storage Class An extern declaration may occur anywhere, but is most often found in the global declaration area. extern is the default for globally declared variables extern is the default for functions. References to external variable and function names are resolved by the linker. For any extern variable: There must be one defining declaration; There may be many referencing declarations. For an external variable in any environment: A defining declaration is a global declaration that omits the extern keyword and gives the variable an initial value. A referencing declaration includes the extern keyword and does not give the variable an initial value. Defining declarations must occur in a source (.c) file. Referencing declarations should occur in a header (.h) file. The result of having two defining instances of a single external variable is undefined and environment dependent. Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/060ClassesAndTypes/140Extern.html [3/29/2008 9:57:51 AM]

26 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers External (extern) Storage Class module.h #ifndef MODULE_H #define MODULE_H extern int factor_g; #endif module.c #include <module.h> int factor_g = 3; void funka( void )... source1.c #include <module.h> void funk1a( void ) int radius = 3 * factor_g;... source2.c #include <module.h> void funk2a( void ) int height = 3 * factor_g;... Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/060ClassesAndTypes/150Extern.html [3/29/2008 9:57:51 AM]

27 Storage Classes and Types Storage Classes and Types static Storage Class Used in the global area static overrides the default storage class (extern) for a variable or function declaration. Used in a block static overrides the default storage class (auto) for a variable declaration. Storage for a static variable is allocated once. sourc1.c static int num_ = 3; static void print_err( void )... source2.c static double num_ = 2.4; static void print_err( void )... source3.c static char *num_ = "118"; static void print_err( int errnum )... source4.c static short num_ = "127"; static int print_err( char *error )... Storage Classes and Types file:///c /Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/060ClassesAndTypes/160Static.html [3/29/2008 9:57:51 AM]

28 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers register Storage Class This storage class may be applied only to function parameters and block-level variables. register implies auto. You may not compute the address of a register variable. register is a "hint" to the compiler that a variable should be stored in a hardware register. The compiler may ignore the hint; it may limit the number of allowed register variables, and may limit the types of variables that can be stored in a register (int is always allowed). static void funk( void ) register int inx = 0; for ( inx = 0 ; inx < ; ++inx )... Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...rk/AdvancedC/Binders/060ClassesAndTypes/170Register.html [3/29/2008 9:57:51 AM]

29 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers typedef Storage Class This storage class specifier indicates that an identifier is a data type rather than a variable or a function. A typedef declaration never allocates storage. typedef int BOOL_t; Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/060ClassesAndTypes/180Typedef.html [3/29/2008 9:57:52 AM]

30 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers const Type Qualifier Any variable or function parameter may be declared to be type const. This type qualifier tells the compiler that the value of a variable or parameter will not be changed. The compiler cannot guarantee that a const storage location will not be modified. With respect to pointers: const type *ptr; Declares a pointer to a constant type. (The storage indicated by ptr may or may not be const; in either case ptr may not be used to modify the storage.) type *const ptr; Declares a constant pointer to a (non-constant) type. (ptr may be used to modify whatever it points to, but ptr itself may not be changed.) int main ( int argc, char **argv ) char str[] = "go dog, go!"; const char *pcstr = str; char *const cpstr = str; char alpha = '\000'; *pcstr++ = 'A'; /* NOT ALLOWED */ alpha = *pcstr++; /* ALLOWED */ *cpstr = 'B'; /* ALLOWED */ *cpstr++ = 'B'; /* NOT ALLOWED */ return EXIT_SUCCESS; Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/060ClassesAndTypes/200Const.html [3/29/2008 9:57:52 AM]

31 Storage Classes and Type Qualifiers Storage Classes and Type Qualifiers volatile Type Qualifier This type qualifier may be used with any variable declaration. A declaration of volatile tells the compiler that the value of the designated variable may change in unexpected way, and therefore is ineligible for certain types of optimization. volatile is used only in esoteric applications and you may very well never need it. void funk( void ) /* pregister is a pointer to a hardware register * that can change at any time. */ volatile short *pregister = (short *) ;... Storage Classes and Type Qualifiers file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...rk/AdvancedC/Binders/060ClassesAndTypes/210Volatile.html [3/29/2008 9:57:52 AM]

32 Topics Functions Pointers to Functions Passing Returning file:///c /Documents%20and%20Settings/Jack%20Straub/My%20...cedC/Binders/070FunctionPointers/110FunctionPointers.html [3/29/2008 9:57:53 AM]

33 Functions The type of a function is the type of value it returns in conjunction with the number and type of its parameters. /* Function type: * function having int, char* and double parameters * and returning type unsigned int. */ unsigned funk( int, char*, double ); The return type of a function may be anything except: array; and function (A function may return a pointer to an array or a pointer to a function.) typedef unsigned FUNC_TYPE_t( int, char*, double ); typedef FUNC_TYPE_t *FUNC_TYPE_p_t; int[4] funk1( void ); /* NOT ALLOWED: returning array */ int *funk2( void ); /* ALLOWED: returning pointer to array */ FUNC_TYPE_t funk3( void ); /* NOT ALLOWED: returning function */ FUNC_TYPE_p_t funk4( void ); /* ALLOWED: returning pointer to function */ A function may be called or invoked by appending the function operator to the function name and enclosing arguments the number and type of which correspond to the type of the function. int funke( int, const char*, double ); int inx = funke( 5, "spot", 3.14 ); (continued...) file:///c /Documents%20and%20Settings/Jack%20Straub/My%2.../AdvancedC/Binders/070FunctionPointers/120Functions.html [3/29/2008 9:57:53 AM]

34 Functions (continued) The name of a function may be assigned to a pointer of the appropriate type, in which case the function name is converted to the address of the function. int funke( int, const char*, double ); int (*fp1)( int, const char*, double ) = funke; /* ALLOWED */ int (*fp2)( const char*, double ) = funke; /* NOT ALLOWED */ char *fp3 = funke; /* NOT ALLOWED */ The name of a function may be used as an argument to another function provided its type matches the type of the corresponding function parameter; in this case the name of the function is converted to the address of the function. int funke( int parm1, int (*parm2)( int, const char*, double ) ); int funkf( int, const char*, double ); void funkg( int, const char*, double ); int inx = funke( 5, funkf ); /* ALLOWED */ int jnx = funke( 5, funkg ); /* NOT ALLOWED */ The name of a function may not be used as the operand of the sizeof operator. The address of a function may not be converted to a void pointer. int funke( int, const char*, double ); size_t inx = sizeof(funke); /* NOT ALLOWED */ void *ptr = funke; /* NOT ALLOWED */ file:///c /Documents%20and%20Settings/Jack%20Straub/My%2.../AdvancedC/Binders/070FunctionPointers/130Functions.html [3/29/2008 9:57:53 AM]

35 Interpreting Declarations: the Right to Left Rule 1. Find the identifier. 2. Move to the right identifying operators and types until you hit a right parenthesis, an equal sign, or the end of the expression. (Note: a left parenthesis at this point denotes the start of the function operator; the matching right parenthesis is the end of the function operator, not a stopping point.) 3. Move to the left of the identifier, interpreting types and operators until you hit the beginning of the expression, or a left parenthesis. 4. Continue to the right where you left off. int inx = 0; ^ inx is... ^ an int int *pinx = NULL; ^ pinx is... ^ a pointer... ^ to an int int funk( void ); ^ funk is... ^------^ a function ^ returning int int (*funk)( void ); ^ funk is... file:///c /Documents%20and%20Settings/Jack%20Straub/M...C/Binders/070FunctionPointers/140RightToLeftRule.html (1 of 2) [3/29/2008 9:57:54 AM]

36 ^ a pointer... ^------^ to a function... ^ returning int (continued...) file:///c /Documents%20and%20Settings/Jack%20Straub/M...C/Binders/070FunctionPointers/140RightToLeftRule.html (2 of 2) [3/29/2008 9:57:54 AM]

37 Interpreting Declarations: the Right to Left Rule (continued) void (*signal(int sig, void (*func)(int)))(int); ^ signal is... ^ ^ a function... ^ returning a pointer... ^---^ to a function... ^ returning void More specifically: void (*signal(int sig, void (*func)(int)))(int); ^ signal is... ^ ^ a function... ^ whose first parameter is an int... ^ and whose second parameter... ^ is a pointer... ^---^ to a function... ^ that has one int parameter... ^ and returns void ^ the return type of signal is a pointer... ^---^ to a function... ^ that has one int parameter... ^ and returns void file:///c /Documents%20and%20Settings/Jack%20Straub/My%2...cedC/Binders/070FunctionPointers/150RightToLeftRule.html [3/29/2008 9:57:54 AM]

38 A Better Way "Signal is a function that returns... [a pointer to a function with an int parameter that return void]... Signal has [an int parameter]... and a parameter which is... [a pointer to a function with an int parameter that return void] /* Type: function with an int parameter * that returns void. */ typedef void SIGNAL_PROC_t( int ); /* Type: pointer to a function with an * int parameter that returns void. */ typedef SIGNAL_PROC_t *SIGNAL_PROC_p_t; SIGNAL_PROC_p_t signal( int, SIGNAL_PROC_p_t ); (continued...) file:///c /Documents%20and%20Settings/Jack%20Straub/My%...dvancedC/Binders/070FunctionPointers/160ABetterWay.html [3/29/2008 9:57:54 AM]

39 A Better Way (continued) /* Instead of this */ struct test_descriptor int args[10]; int num_args; int result; int (*test_proc)( int *args, int num_args ); ; static int test01( int *args, int num_args ); static int test02( int *args, int num_args );... static int test20( int *args, int num_args ); /* Try this */ typedef int TEST_PROC_t( int *args, int num_args ); typedef TEST_PROC_t *TEST_PROC_p_t; struct test_descriptor int args[10]; int num_args; int result; TEST_PROC_p_t test_proc; ; static TEST_PROC_t test01; static TEST_PROC_t test02;... static TEST_PROC_t test20; file:///c /Documents%20and%20Settings/Jack%20Straub/My%...dvancedC/Binders/070FunctionPointers/170ABetterWay.html [3/29/2008 9:57:54 AM]

40 Usually point to a block of memory containing information about how to invoke a function. May not be used in pointer arithmetic. file:///c /Documents%20and%20Settings/Jack%20Straub/My%20...cedC/Binders/070FunctionPointers/180FunctionPointers.html [3/29/2008 9:57:55 AM]

41 Using typedef int TEST_PROC_t( void ); typedef TEST_PROC_t *TEST_PROC_p_t; typedef struct test_desc_s const char *description; TEST_PROC_p_t proc; TEST_DESC_t, *TEST_DESC_p_t; static TEST_PROC_t test01; static TEST_PROC_t test02; static TEST_PROC_t test03; static TEST_DESC_t all_tests_[] = "This is test #1", test01, "This is test #2", test02, "This is test #3", test03 ; static num_tests_ = sizeof(all_tests_)/sizeof(*all_tests_); int main( int argc, char **argv ) int result = EXIT_SUCCESS; TEST_DESC_p_t test = all_tests_; int inx = 0; for ( inx = 0 ; inx < num_tests_ && result == EXIT_SUCCESS ; ++inx ) printf( "%s... ", test[inx].description ); if ( test[inx].proc() ) printf( "SUCCESS\n" ); else printf( "FAILURE\n" ); result = EXIT_FAILURE; return result; static int test01( void ) return 1; static int test02( void ) file:///c /Documents%20and%20Settings/Jack%20Straub/My...ders/070FunctionPointers/190UsingFunctionPointers.html (1 of 2) [3/29/2008 9:57:55 AM]

42 return 1; static int test03( void ) return 1; $./a This is test #1... SUCCESS This is test #2... SUCCESS This is test #3... SUCCESS file:///c /Documents%20and%20Settings/Jack%20Straub/My...ders/070FunctionPointers/190UsingFunctionPointers.html (2 of 2) [3/29/2008 9:57:55 AM]

43 Passing static int sensitive_sort( const void*, const void* ); static int insensitive_sort( const void*, const void* ); static char *names_[] = "TOM", "dick", "harry" ; static size_t num_names_ = sizeof(names_)/sizeof(*names_); int main( int argc, char **argv ) int result = EXIT_SUCCESS; int (*sort)( const void*, const void* ) = NULL; if ( argc!= 2 ) usage(); result = EXIT_FAILURE; else if ( strcmp( argv[1], "case-sensitive" ) ) sort = sensitive_sort; else if ( strcmp( argv[1], "case-insensitive" ) ) sort = insensitive_sort; else usage(); result = EXIT_FAILURE; if ( result == EXIT_SUCCESS ) qsort( names_, num_names_, sizeof(char*), sort ); print_names(); return result; /* perform a case-sensitive comparison of two names */ static int sensitive_sort( const void *name1, const void *name2 ) file:///c /Documents%20and%20Settings/Jack%20Straub/My...rs/070FunctionPointers/200PassingFunctionPointers.html (1 of 2) [3/29/2008 9:57:55 AM]

44 ... /* perform a case-insensitive comparison of two names */ static int insensitive_sort( const void *name1, const void *name2 )... file:///c /Documents%20and%20Settings/Jack%20Straub/My...rs/070FunctionPointers/200PassingFunctionPointers.html (2 of 2) [3/29/2008 9:57:55 AM]

45 Returning static void log_stderr( const char *,... ); static void log_syslog( const char *,... ); static void (*set_log( int argc, char **argv ))( const char *,... ); int main( int argc, char **argv ) int result = EXIT_SUCCESS; void (*log)( const char*,... ) = set_log( arg, argv ); funk1( log );... return result; static void (*set_log( int argc, char **argv ))( const char *,... ) void (*log)( const char*,... ) = log_syslog; if ( argc > 1 && strcmp( argv[1], "-debug" ) == 0 ) log = log_stderr; return log; file:///c /Documents%20and%20Settings/Jack%20Straub/My%20...ers/070FunctionPointers/210ReturningFunctionPointers.html [3/29/2008 9:57:56 AM]

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Exercise Session 2 Simon Gerber

Exercise Session 2 Simon Gerber Exercise Session 2 Simon Gerber CASP 2014 Exercise 2: Binary search tree Implement and test a binary search tree in C: Implement key insert() and lookup() functions Implement as C module: bst.c, bst.h

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation ... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015 ... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

ECE264 Spring 2013 Final Exam, April 30, 2013

ECE264 Spring 2013 Final Exam, April 30, 2013 ECE264 Spring 2013 Final Exam, April 30, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

CS107, Lecture 9 C Generics Function Pointers

CS107, Lecture 9 C Generics Function Pointers CS107, Lecture 9 C Generics Function Pointers Reading: K&R 5.11 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All

More information

1. We have a code sequence that is potentially executed twice.

1. We have a code sequence that is potentially executed twice. Long Jump Long Jump Local Jumps In the following example: 1. We have a code sequence that is potentially executed twice. 2. A flag is used to determine whether the sequence is being executed the first

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

C Programming Review CSC 4320/6320

C Programming Review CSC 4320/6320 C Programming Review CSC 4320/6320 Overview Introduction C program Structure Keywords & C Types Input & Output Arrays Functions Pointers Structures LinkedList Dynamic Memory Allocation Macro Compile &

More information

CSE 333 Midterm Exam Sample Solution 7/28/14

CSE 333 Midterm Exam Sample Solution 7/28/14 Question 1. (20 points) C programming. For this question implement a C function contains that returns 1 (true) if a given C string appears as a substring of another C string starting at a given position.

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

o Code, executable, and process o Main memory vs. virtual memory

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/16 1-dimensional Arrays Arrays can be statically declared in C, such as: int A [100]; The space for this

More information

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites: C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

CS 107 Lecture 5: Arrays. and Pointers in C. Monday, January 22, Stanford University. Computer Science Department

CS 107 Lecture 5: Arrays. and Pointers in C. Monday, January 22, Stanford University. Computer Science Department CS 107 Address Value Lecture 5: Arrays 8 and Pointers in C 0x128 3 0x120 Monday, January 22, 2018 9 0x118 Computer Systems Winter 2018-4 Stanford University 0x110 Computer Science Department 2 Reading:

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

CSE 333 Midterm Exam Sample Solution 5/10/13

CSE 333 Midterm Exam Sample Solution 5/10/13 Question 1. (18 points) Consider these two C files: a.c void f(int p); int main() { f(17); return 0; b.c void f(char *p) { *p = 'x'; (a) Why is the program made from a.c and b.c incorrect? What would you

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

ECE264 Spring 2014 Exam 2, March 11, 2014

ECE264 Spring 2014 Exam 2, March 11, 2014 ECE264 Spring 2014 Exam 2, March 11, 2014 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array

More information

C++ Tutorial AM 225. Dan Fortunato

C++ Tutorial AM 225. Dan Fortunato C++ Tutorial AM 225 Dan Fortunato Anatomy of a C++ program A program begins execution in the main() function, which is called automatically when the program is run. Code from external libraries can be

More information

My malloc: mylloc and mhysa. Johan Montelius HT2016

My malloc: mylloc and mhysa. Johan Montelius HT2016 1 Introduction My malloc: mylloc and mhysa Johan Montelius HT2016 So this is an experiment where we will implement our own malloc. We will not implement the world s fastest allocator, but it will work

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

C Legacy Code Topics. Objectives. In this appendix you ll:

C Legacy Code Topics. Objectives. In this appendix you ll: cppfp2_appf_legacycode.fm Page 1 Monday, March 25, 2013 3:44 PM F C Legacy Code Topics Objectives In this appendix you ll: Redirect keyboard input to come from a file and redirect screen output to a file.

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Carnegie Mellon. C Boot Camp. Oct 6th, Jack Biggs Raghav Goyal Nikhil Jog

Carnegie Mellon. C Boot Camp. Oct 6th, Jack Biggs Raghav Goyal Nikhil Jog C Boot Camp Oct 6th, 2017 Jack Biggs Raghav Goyal Nikhil Jog Agenda C Basics Debugging Tools / Demo Appendix C Standard Library getopt stdio.h stdlib.h string.h C Basics Handout ssh @shark.ics.cs.cmu.edu

More information

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler) 1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

Advanced Pointer Topics

Advanced Pointer Topics Advanced Pointer Topics Pointers to Pointers A pointer variable is a variable that takes some memory address as its value. Therefore, you can have another pointer pointing to it. int x; int * px; int **

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam Name: ECE 551D Spring 2018 Midterm Exam NetID: There are 6 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

Memory Management I. two kinds of memory: stack and heap

Memory Management I. two kinds of memory: stack and heap Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation)

More information

POINTER AND ARRAY SUNU WIBIRAMA

POINTER AND ARRAY SUNU WIBIRAMA POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program

More information

Arrays, Strings, and Pointers

Arrays, Strings, and Pointers Arrays, Strings, and Pointers Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 04 BE5B99CPL C Programming Language Jan Faigl, 2017

More information

ECE 15B COMPUTER ORGANIZATION

ECE 15B COMPUTER ORGANIZATION ECE 15B COMPUTER ORGANIZATION Lecture 13 Strings, Lists & Stacks Announcements HW #3 Due next Friday, May 15 at 5:00 PM in HFH Project #2 Due May 29 at 5:00 PM Project #3 Assigned next Thursday, May 19

More information

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings Lecture 4: Outline I. Pointers A. Accessing data objects using pointers B. Type casting with pointers C. Difference with Java references D. Pointer pitfalls E. Use case II. Arrays A. Representation in

More information

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

A S H O R T I S H O V E R V I E W O F T H E A N S I C P R O G R A M M I N G L A N G U A G E

A S H O R T I S H O V E R V I E W O F T H E A N S I C P R O G R A M M I N G L A N G U A G E A S H O R T I S H O V E R V I E W O F T H E A N S I C P R O G R A M M I N G L A N G U A G E IDENTIFIERS Identifiers are names of variables, functions, defined types, structures and unions, enumeration

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

Ch. 3: The C in C++ - Continued -

Ch. 3: The C in C++ - Continued - Ch. 3: The C in C++ - Continued - QUIZ What are the 3 ways a reference can be passed to a C++ function? QUIZ True or false: References behave like constant pointers with automatic dereferencing. QUIZ What

More information

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Pointers, Arrays, Memory: AKA the cause of those Segfaults Computer Science 61C Spring 2018 Wawrzynek and Weaver Pointers, Arrays, Memory: AKA the cause of those F@#)(#@*( Segfaults 1 Agenda Computer Science 61C Spring 2018 Pointers Arrays in C Memory Allocation

More information

Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08

Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08 Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08 For your solutions you should submit a hard copy; either hand written pages stapled together or a print out of a typeset document

More information

Memory (Stack and Heap)

Memory (Stack and Heap) Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

Carnegie Mellon. C Boot Camp. September 30, 2018

Carnegie Mellon. C Boot Camp. September 30, 2018 C Boot Camp September 30, 2018 Agenda C Basics Debugging Tools / Demo Appendix C Standard Library getopt stdio.h stdlib.h string.h C Basics Handout ssh @shark.ics.cs.cmu.edu cd ~/private wget

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Arrays, Strings, and Pointers

Arrays, Strings, and Pointers Arrays, Strings, and Pointers Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 04 B3B36PRG C Programming Language Jan Faigl, 2018

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

Fall 2018 Discussion 2: September 3, 2018

Fall 2018 Discussion 2: September 3, 2018 CS 61C C Basics Fall 2018 Discussion 2: September 3, 2018 1 C C is syntactically similar to Java, but there are a few key differences: 1. C is function-oriented, not object-oriented; there are no objects.

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

Arrays, Strings, and Pointers

Arrays, Strings, and Pointers Arrays, Strings, and Pointers Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 04 BE5B99CPL C Programming Language Jan Faigl, 2017

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information

JTSK Programming in C II C-Lab II. Lecture 3 & 4

JTSK Programming in C II C-Lab II. Lecture 3 & 4 JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically

More information

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C C strings (Reek, Ch. 9) 1 Review of strings Sequence of zero or more characters, terminated by NUL (literally, the integer value 0) NUL terminates a string, but isn t part of it important for strlen()

More information

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12 Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming Procedural Programming & Fundamentals of Programming Exercise 3 (SS 2018) 29.05.2018 What will I learn in the 4. exercise Pointer (and a little bit about memory allocation) Structure Strings and String

More information

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. Name: ECE551 Midterm NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual work. You

More information

CS201: Lab #4 Writing a Dynamic Storage Allocator

CS201: Lab #4 Writing a Dynamic Storage Allocator CS201: Lab #4 Writing a Dynamic Storage Allocator In this lab you will write a dynamic storage allocator for C programs, i.e., your own version of the malloc, free and realloc routines. You are encouraged

More information

edunepal_info

edunepal_info facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced

More information

COSC Software Engineering. Lecture 16: Managing Memory Managers

COSC Software Engineering. Lecture 16: Managing Memory Managers COSC345 2013 Software Engineering Lecture 16: Managing Memory Managers Outline Typical problems (from previous lectures) Memory leaks aren t just for (Objective) C Tracking malloc() calls Catching calls

More information

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 C Strings, Arrays, & Malloc 2007-06-27 Scott Beamer, Instructor Sun announces new supercomputer: Sun Constellation CS61C L3 C Pointers

More information

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan Operating Systems 2INC0 C course Pointer Advanced Dr. Ir. Ion Barosan (i.barosan@tue.nl) Containt Pointers Definition and Initilization Ponter Operators Pointer Arithmetic and Array Calling Functions by

More information

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS C Programming C SYLLABUS COVERAGE Introduction to Programming Fundamentals in C Operators and Expressions Data types Input-Output Library Functions Control statements Function Storage class Pointer Pointer

More information

Here's how you declare a function that returns a pointer to a character:

Here's how you declare a function that returns a pointer to a character: 23 of 40 3/28/2013 10:35 PM Violets are blue Roses are red C has been around, But it is new to you! ANALYSIS: Lines 32 and 33 in main() prompt the user for the desired sort order. The value entered is

More information

CS24 Week 2 Lecture 1

CS24 Week 2 Lecture 1 CS24 Week 2 Lecture 1 Kyle Dewey Overview C Review Void pointers Allocation structs void* (Void Pointers) void* Like any other pointer, it refers to some memory address However, it has no associated type,

More information

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Agenda Pointers Arrays in C 2 Address vs. Value Consider

More information

Recitation #11 Malloc Lab. November 7th, 2017

Recitation #11 Malloc Lab. November 7th, 2017 18-600 Recitation #11 Malloc Lab November 7th, 2017 1 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than 32 bit Encourages

More information