Posts

Showing posts with the label C programming

Where C Variables are Stored in Memory

Image
Memory sections stack - the portion of memory that stores variables that were declared inside functions (i.e. stores local variables and constants) local variables are freed when the function returns (these variables cannot be accessed once the function ends) Stack memory grows downward heap - the portion of memory that stores things that were created by malloc() Data on the heap persists across functions (unlike the local variables of stack memory) Heap memory grows upward static - the portion of memory that stores "pre-allocated" variables including static and global variables (variables declared outside functions), constants, and string literals  Two sections of static memory:  read-only (stores variables that can only be read and not modified) read-write (stores variables that can be both read and written to (modified)) Static memory does not grow or shrink code (text) - the portion of memory that stores the executable instructions and constants C...

Tips on Pointers and Arrays in C

Image
*p++ vs. (*p)++   *p++ means *(p++) ++ binds to p , not to *p ++ will increment "p," not "*p," which is the thing that "p" points to The value of the expression *p++ is the value that p pointed to before being incremented ( *p ) Two useful charts Pointer arithmetic notes (~pointer~) += (~number~);  means  (~pointer~) += ~number~) * sizeof((~type~)); Pointer arithmetic addition adds multiples of the type size to the memory address Ex. If p is a pointer to an integer, then p += 1 means p += 1 * sizeof(int)   (~pointer name~) + 1 points to the next object in memory (returns a pointer to the next element)  (~pointer name~) + i points to the i -th object beyond (~pointer name~) in memory  (~pointer name~) += i increments (~pointer name~) to point to i elements beyond itself  Types of valid pointer arithmetic Adding an integer to a pointer Subtracting 2 pointers (in the same array) Comparing...