mirror of
https://github.com/janishutz/eth-summaries.git
synced 2026-01-12 14:18:23 +00:00
[SPCA] Finish pointers section
This commit is contained in:
@@ -1,6 +1,12 @@
|
||||
#include "01_func.h" // See a few pages up for declarations
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
void a_function( int ( *func )( char * ), char prompt[] ) {
|
||||
( *func )( prompt ); // Call function with arguments
|
||||
}
|
||||
|
||||
int main( int argc, char *argv[] ) {
|
||||
int x = 0;
|
||||
int *p = &x; // Get x's memory address
|
||||
@@ -11,8 +17,7 @@ int main( int argc, char *argv[] ) {
|
||||
int *null_p = NULL; // Create NULL pointer
|
||||
*null_p = 1; // Segmentation fault due to null pointer dereference
|
||||
|
||||
// ── pointer arithmetic ───────────────────────────────────────────
|
||||
// Already seen a bit in the c arrays section
|
||||
// pointer arithmetic
|
||||
int arr[ 3 ] = { 2, 3, 4 };
|
||||
char c_arr[ 3 ] = { 'A', 'B', 'C' };
|
||||
int *arr_p = &arr[ 1 ];
|
||||
@@ -22,6 +27,11 @@ int main( int argc, char *argv[] ) {
|
||||
|
||||
char *arr_p_c = (char *) arr_p; // Cast to char pointer (points to first byte of arr[0])
|
||||
printf( "%d", *( arr_p - 5 ) ); // No boundary checks (can access any memory)
|
||||
assert( arr == &( arr[ 0 ] ) ); // Evaluates to true
|
||||
int new_arr[ 3 ] = arr; // Compile time error (cannot use other array as initializer)
|
||||
int *new_arr_p = &arr[ 0 ]; // This works
|
||||
|
||||
a_function( &get_user_input_int, c_arr );
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user