--- tags: CS50’s Introduction to CS --- # Week 4 ## Pointers 1. Introduction: Most of the time, main memory is divided into bytes, and each byte has a address. These addresses can be stored in special pointer variables. When we store the address of a variable i in the pointer variable p, we say that p points to i. 2. Declaration: ```c int *v_name; ``` v_name is a pointer variable capable of pointing to objects of type int. 3. Operations: 1. To find the address of a variable, we use the & operator. ```c &v_name ``` 2. To gain access to the object that a pointer points to, we use the * operator. ```c *v_name ``` 3. To point the pointer to the an address, we write ```c v_name=address; ``` 4. As long as a pointer p points to a int i, then changing the value of *p changes the value of i. 5. %p is a conversion specifications that can print out an address. 4. Initializing: ```c int i,*p; p=&i; ``` ```c int i; int *p=&i; ``` 5. Pointer and Function: 1. Pointers as Arguments: ```c //Declaration type function_name(data_type *...) //Definiton type function_name(data_type *v1...) { ... } //Call function_name(v1...) //v1 must be an address. ``` * ※If the values that the pointers point to are changed in functions, it will also affact original variables. 2. Pointers as Return Values ```c type *functoion_name(...) ``` 6. Pointers and Arrays 1. Introduction: 1. C allows us to perform addition and subtraction on pointers to array elements, this leads to an alternative way of processing arrays in which pointers take the place of array subscripts 2. Pointers can point to array elements, and the names of the arrays represent the first elements of the arrays. 2. Operations: 1. Arithmetic Operation: 1. Adding or Subtracting an Integer to a Pointer: Adding or subtracting an integer j to a pointer p yields a pointer to the element j places after or before the one that p points to. 2. Subtracting One Pointer from Another: When one pointer is subtracted from another, the result is the distance between the pointers. * ※Only meaningful for pointers to elements of the same array. 2. Comparing Pointers: Pointers can be compared using <, <=, >, >=, == and !=. The outcome depends on the relative positions of the two elements in the array. 7. Dynamic Storage Allocation 1. Introduction: C's data structures, including arrays, are normally fixed in size. Fortunately, C supports dynamic storage allocation. Using dynamic storage allocation, we can design data structures that grow and shrink as needed. 2. Memory Allocation Functions The <stdlib.h> header declears three memory allocation functions: 1. malloc(size): malloc() allocates a block of memory but doesn't initialize it(faster). * ※Memory allocated using malloc isn't cleared, so p will point to an uninitialized array. Calling strcpy is one way to initialize the array. 2. calloc(): ```c void *calloc(size_t nmemb, size_t size); ``` calloc() 1. allocates space for an array with nmemb elements, each of which is size bytes long, 2. returns a null pointer if the requested space isn't available, 3. and initializes allocated memory by setting all bits to 0. 3. realloc(): ```c void *realloc(void *ptr, size_t size); ``` 1. ptr must point to a memory block obtained by a previous call of malloc, calloc, or realloc. 2. size represents the new size of the block, which may be larger or smaller than the original size. 3. When it expands a memory block, realloc doesn't initialize the bytes that are added to the block. 4. If realloc can't enlarge the memory black as requested, it returns a null pointer; the data in the old memory block is unchanged. 5. If realloc is called with a null pointer as its first argument, it behaves like malloc. 6. If realloc is called with 0 as its second arguments, it frees the memory block. 7. If it can't enlarge a block, realloc will allocate a new block elsewhere, then copy the contents of the old block into the new one. 4. free(): ```c void free(void *ptr); ``` Calling free releases the block of memory that p points to. * ※free( p ) deallocates the memory block that p points to, but doesn't change p itself. * ※These functions return a value of type void * * ※If a memory allocation function can't locate a memory block of the requested size, it returns a null pointer. A null pointer is a special value that can be distinguished from all valid pointers. And ```c NULL ``` is a macro that represents the null pointer. * ※All non-null pointers test true; only null pointers are false. * ※Memory allocation functions obtain memory blocks from a storage pool known as the heap. Calling these functions too often or asking them fro large blocks of memory can exhaust the heap, causing the functions to return a null pointer. A block of memory that's no longer accessible to a program is said to be garbage, and a program that leaves garbage behind has a memory leak. 3. Organization: Dynamically allocated memory comes from a pool of memory knowns as the heap. * ※Dynamic storage allocation is especially useful for building lists, trees, graphs, and other linked data structures. ## Program Organization: 1. Variables: 1. Local Variables(& Parameters): A variable declared in the body of a function is said to be local to the function. 1. Automatic Storage Duration: Storage is automatically allocated when the enclosing function is called and deallocated when the function returns. 2. Block Scope: A local variable is visible from its point of declaration to the end of the enclosing function body. 2. Static Local Variables: Including static in the declaration of a local variable can create a static variable , causeing it to have static storage duration. 1. Static Storage Duration: A varialbe with static storage duration has a permanent storage location, so it retains its value throughout the execution of the program. 2. A static local variable still has block scope. 3. External Variables(Global Variables): External variables are declared outside the body of any function. 1. Static Storage Duration: 2. File Scope: An external variable is visible from its point of declaration to the end of the enclosing file. 2. Memory Layout ![](https://i.imgur.com/dtfeN3J.png) * Call Stack: 1. Introduction: When you call a function, the system sets aside space in memory for that function to do its necessary work. We frequently call such chunks of memory stack frams or function frams. 2. Procedures: 1. These frams are arranged in a stack. The frame for the most recently called function is always on the top of the stack. 2. When a new function is called, a new frame is **pushed** onto the top of the stack and becomes the active frame. 3. When a function finishes its work, ots frame is **popped** off of the stack, and the frame immediately below it becomes the new, active function on the top of the stack. This function picks up immediately where it left off. ## File 1. Introductions 1. The ability to read data from and write data to files is the primary means of storing **persistent data**, data that does not disappear when your program stops running. 2. THe abstraction of files that C provides is implemented in a data structure known as a FILE. While almost universally when working with files, we will be using pointers to them, FILE *. 2. Manipulation The file manipulation functions all live in <stdio.h> and all of them accecp FILE * as one of their parameters, except for the function fopen(), which is used to get a file pointer in the first place. 1. fopen(): fopen() opens a file and returns a file pointer to it. ```c FILE *ptr=fopen(<filename>,<operatoion>); ``` * Operations: | Operations | Description | | :-: | :- | | "w" | Open a text file for writing. If the w mode is specified for a ddname that has DISP=MOD, the behavior is the same as if a had been specified. Otherwise, if the file already exists, its contents are destroyed.| | "r" |Open a text file for reading. (The file must exist.)| | "a" |Open a text file in append mode for writing at the end of the file. fopen() creates the file if it does not exist.| | "r+" |Open a text file for both reading and writing. (The file must exist.)| | "w+" |Open a text file for both reading and writing. If the w+ mode is specified for a ddname that has DISP=MOD, the behavior is the same as if a+ had been specified. Otherwise, if the file already exists, its contents are destroyed.| | "a+" |Open a text file in append mode for reading or updating at the end of the file. fopen() creates the file if it does not exist.| * ※Always check the return value to make sure you don't get back NULL. 2. fclose(): Closes the file pointed to by the given file pointer. ```c fclose(<file pointer>); ``` 3. fgetc(): fgetc() reads and returns the next character from the file pointed to. ```c char ch = fgetc(<file pointer>); ``` * ※A program that can print out all of the characters in the file: ```c char ch; while((ch=fgetc(<file pointer>))!= EOF) print("%c",ch); ``` 4. fputc(): fputc() writes appends the specified character to the pointed-to file. ```c fputc(<character>,<file pointer>); ``` 5. fread(): fread() reads <qty> units of size <size> from the file pointed to and stores them in memory in a buffer pointed to by <buffer>. ```c fread(<buffer>,<size>,<qty>,<file pointer>); ``` 6. fwrite(): fwrite() writes <qty> units of size <size> to the file pointed to by reading them from a buffer pointed to by <buffer>. ```c fwrite(<buffer>,<size>,<qty>,<file pointer>); ``` 7. fgets(): fgets() reads a full string from a file. 8. fputs(): fputs() writes a full string to a file. 9. fprintf(): fprintf() writes a formatted string to a file. 10. fseek(): fseek() allows tou rewind or fast-forward within a file. 11. ftell(): ftell() tells you at what (byte) position you are at within a file. 12. feof(): feof() tells you whether you've read to the end of a file. 13. ferror(): ferror() indicates whether an error has occurred in working with a file. **Reference** [Memory Layout of C program - Aticleworld](https://www.google.com/search?q=c+memory+organization&sxsrf=AOaemvLSWuQ-uHR9dhwiLm_QqPWnUx0g5w%3A1631966855136&ei=h9ZFYazZB8iJhwPRxZ-wDg&oq=c+memory+or&gs_lcp=Cgdnd3Mtd2l6EAMYADIFCAAQywEyBQgAEMsBMgYIABAIEB4yBggAEAgQHjIGCAAQCBAeMgYIABAIEB4yBggAEAgQHjIGCAAQCBAeMgYIABAIEB46BQgAEIAEOgQIABAeSgQIQRgAUMocWNgfYPUoaABwAHgAgAFtiAG6AZIBAzEuMZgBAKABAcABAQ&sclient=gws-wiz) CS50’s Introduction to CS [fopen() — Open a file - IBM](https://www.ibm.com/docs/en/zos/2.4.0?topic=functions-fopen-open-file)