SlideShare a Scribd company logo
Pointers
Heap & Pointers
● Types of storage:
– global (defined in the static data segment)
– automatic or local (defined in the program stack)
– dynamic
● Dynamic memory blocks required by the program(mer) come from a memory pool
called a heap—they are allocated and deallocated
● C does not have garbage collection. All allocated variables must be deallocated by the
program(mer)
● A pointer is a variable whose value is a memory address representing the allocated
memory block
Declaring a Pointer
● Different types of pointers required for different data blocks:
– int *p; /* An uninitialized pointer to an integer number or an
array of integer numbers of size sizeof(int) */
– char *s; /* A pointer to a character array—a string (if NULL-
terminated) */
– void *v; /* An unstructured uninitialized pointer—USE WITH
CAUTION! */
– int *p1, *p2, p3; /* Two integer pointers and an integer */
– int **pp; /* A pointer to a pointer */
– double ***foo; /* A pointer to a pointer to a double pointer */
● Types of pointers can be modified by casting:
– int *p = …;
– char *c = (char *)p; /* Now, c points to the first byte of the
number! */
– c++; /* Now, it points to the second byte! */
● Casting pointers should be avoided.
Declaring a Pointer
● Different types of pointers required for different data blocks:
– int *p; /* An uninitialized pointer to an integer number or an
array of integer numbers of size sizeof(int) */
– int* p1; /* Where and whether you put the space, is up to you */
– char *s; /* A pointer to a character array—a string (if NULL-
terminated) */
– void *v; /* An unstructured uninitialized pointer—USE WITH
CAUTION! */
– int *p1, *p2, p3; /* Two integer pointers and an integer */
– int **pp; /* A pointer to an integer pointer */
– double ***foo; /* A pointer to a pointer to a double pointer */
● Types of pointers can be modified by casting:
– int *p = …;
– char *c = (char *)p; /* Now, c points to the first byte of the
number! */
– c++; /* Now, it points to the second byte! */
● Casting pointers should be avoided.
Initializing a Pointer
● The & operator calculates the address of a static or automatic variable:
– int z = 0;
– int *zp = &z; /* The address of z is now in zp */
– printf (“z=%i, &z=%xn”, z, zp);
● Remember that the address of an automatic variable makes no sense outside of the
function:
– int *foobar (void) {
– int localVar = 617363;
– int *ptr = &localVar;
– return ptr; /* Bad idea! After foobar returns, localVar is no
more!—Unless it's also static */
– }
Dereferencing a Pointer
● To dereference a pointer is to obtain the value of the variable that it refers to. Operator
* dereferences a pointer:
– int var1 = 77, var2;
– int *ptr = &var1;
– var2 = *ptr; /* Now the value of var2 is 77 */
– (*ptr)++; /* Now, var1 is 78 */
– *ptr++; /* Dereference the pointer and then increment it; var1 is
still 78, but ptr changed by 1 */
– (*ptr) = 10; /* Now, var1 is 10 */
● Operators & and *, if properly used, are complementary: *&x is the same as x.
However, &*x is not legal.
“Constant” Pointers
● A pointer to a constant;
– const int *p; /* p can change, but *p cannot */
– int const *p; /* same as above */
● A constant pointer to a variable:
– int *const p; /* *p can change, but p cannot */
● A constant pointer to a constant:
– const int *const p; /* nothing can change */
Generic Pointers
● A generic pointer cannot be dereferenced:
– void *generic = ….;
– *generic = ... /* Illegal */
● Any pointer can be safely cast to a generic pointer:
– int var = 564;
– int *iptr = &var;
– void *generic = (void*)iptr;
● A generic pointer can be cast to a specific pointer of the original type, if known:
– *(int*)generic; /* 564 */
● What's a NULL? It's a macro defined in stdlib.h:
– #define NULL (void*)0
Pointer Arithmetic
● Operators +, -, ++, and – increment/decrement pointers by the number of object sizes:
– char *s = …;
– s++; /* s is incremented by 1 */
–
– int *ptr = …;
– ptr += 2; /* ptr is increased by 2*sizeof(int) */
● Very useful to work with arrays in general and strings (NULL-terminated character
arrays) in particular:
– char *source = “Hello, world”; /* source is the address of the
first element of the string */
– char *dest = …; /* allocate memory for the copy */
– while (*dest++ = *source++); /* copy while not NULL */
● Pointers of the same type can be subtracted, and the difference is the number of
objects between hgem:
– int diff = ptr2 – ptr1;
● Pointers of the same type can be compared with >, >=, <, <=, ==, and !=. Comparing
the pointers does not involve comparing the memory they point to.
Memory Allocation
● Memory allocation functions are defined in stdlib.h. They return a pointer to a freshly
allocated block or NULL in case of failure.
● Function void *malloc(size_t) gets a block of uninitialized memory.
– int *myArray;
– if (NULL == (myArray = malloc (32 * sizeof(int))) {
– perror (“malloc”);
– exit (EXIT_FAILURE);
– }
● Function void *calloc(size_t,size_t) gets a block zero-filled memory.
– if (NULL == (myArray = calloc (32, sizeof(int))) {...
● Function void *realloc(void*, size_t) changes the size of a previously allocated block
and returns a new pointer, if necessary. The content of the block is preserved.
– if (NULL == (myArray = realloc (myArray , 64 * sizeof(int))) {…
● If the return value is not saved, the allocated block is inaccessible (memory leak).
Memory Deallocation
● Any previously allocated block must be deallocated with free():
– free (myArray);
● The value of myArray did not change, but should not be used anymore. For safety,
nullify it:
– myArray = NULL;
Working with Memory Blocks
● memcpy() copies one block to another if they do not overlap
● memmove() copies one block to another; the blocks may overlap
● memcmp() compares two memory blocks, bytewise
● bzero() zero-fills a block
The Mystery of scanf()
● All parameters to scanf, expect for the format string, must be pointers to the previously
allocated storage variables:
– int a;
– double b;
– char c;
– char *str = malloc (128);
– if (4 != scanf (“%i %lf %c %s”, &a, &b, &c, str)) {… /* str is
already a pointer */
The Mystery of FILE*
● FILE* is a pointer to a variable of type FILE, which is defined in stdio.h. In fact, the
standard I/O streams are simply variables of this type:
– FILE *stdin, *stdout, *stderr;
Binary I/O
● Function long ftell(FILE*) returns the current reading/writing position in an open file.
● Function int fseek(FILE*, long offset, int mode) changes the current position in an open
file by offset. The mode can be SEEK_SET (from the beginning of the file), SEEK_CUR
(from the current position) or SEEK_END (from the end of the file).
– fseek (f, sizeof (double), SEEK_CUR); /* go to the next double */
● Function size_t fread(void *buff, size_t size, size_t count, FILE *f) reads size*count
bytes into the previously allocated buffer buff from the previously open file f:
– const int BUFF_SIZE = 1024;
– FILE *infile = fopen(“myfile.txt”, “r”); /* check return value */
– char *data = malloc (BUFF_SIZE); /* check return value */
– if (BUFF_SIZE != fread (data, 1, BUFF_SIZE, infile)) {…
● Function size_t fwrite(void *buff, size_t size, size_t count, FILE *f) writes size*count
bytes from the previously allocated buffer buff to the previously open file f. Both
functions return the number of successfully read/written objects.
Passing Arguments by Reference
● If you pass a pointer to an object to a function, the function can modify the object:
– void addToInt (int *ptr, int change) {
– (*ptr) += change;
– }
– ...
– int val = 10;
– addToInt (&val, 5); /* val is 15 now */
● Always pass large objects (arrays and structs) by reference
● If the object shall not be modified, use a const pointer:
– void functionThatShallNotChangeX (const int* x) { ...
● Pass small objects by reference only when the function shall change their value
Pointers to Blocks of Pointers
● Memory-allocating functions can allocate memory for pointers to other blocks:
– int **table;
– table = malloc (sizeof (int*) * 100); /* a table of 100 integer
pointers */
– for (i = 0; i < 100; i++)
– table[i] = malloc (sizeof (int) * 256); /* each pointer, in
turn, points to a block of 256 integers */
–
– /* Did I tell you that C does to define variables only before the
first executable statement of a function? */
–
– int *q = table[0]; /* the address of the first block */
– int c = table[0][0]; /* the value at the beginning of the first
block */

More Related Content

What's hot

What's hot (19)

Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
C tutorial
C tutorialC tutorial
C tutorial
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
OpenGL ES 3 Reference Card
OpenGL ES 3 Reference CardOpenGL ES 3 Reference Card
OpenGL ES 3 Reference Card
 
Function
FunctionFunction
Function
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
 

Viewers also liked

Verdi in Venice
Verdi in VeniceVerdi in Venice
Verdi in Venice
mariane m
 

Viewers also liked (15)

Verdi in Venice
Verdi in VeniceVerdi in Venice
Verdi in Venice
 
Agile crash course - how to build bad software
Agile crash course - how to build bad softwareAgile crash course - how to build bad software
Agile crash course - how to build bad software
 
Heroes 1 Monstros
Heroes 1 MonstrosHeroes 1 Monstros
Heroes 1 Monstros
 
CVPK2015
CVPK2015CVPK2015
CVPK2015
 
Baiuteii
BaiuteiiBaiuteii
Baiuteii
 
Margravine Menaces
Margravine MenacesMargravine Menaces
Margravine Menaces
 
Green rootz
Green rootz Green rootz
Green rootz
 
October 2016 Newsletter
October 2016 NewsletterOctober 2016 Newsletter
October 2016 Newsletter
 
Soviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success PredictorsSoviet Popular Music Landscape: Community Structure and Success Predictors
Soviet Popular Music Landscape: Community Structure and Success Predictors
 
Circulação lei estadual - 2013 - proposta patrocínio
Circulação   lei estadual - 2013 - proposta patrocínioCirculação   lei estadual - 2013 - proposta patrocínio
Circulação lei estadual - 2013 - proposta patrocínio
 
Selayang Pandang Ethical Fashion
Selayang Pandang Ethical FashionSelayang Pandang Ethical Fashion
Selayang Pandang Ethical Fashion
 
Trabalho de gegrafia
Trabalho de gegrafiaTrabalho de gegrafia
Trabalho de gegrafia
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1
 
Kalev Kaarna "Tootmisjuhtimise tähesupp"
Kalev Kaarna "Tootmisjuhtimise tähesupp"Kalev Kaarna "Tootmisjuhtimise tähesupp"
Kalev Kaarna "Tootmisjuhtimise tähesupp"
 
Tööstuse digitaliseerimisest, Arne Kaasik, 07.12.2016 TSENTER
Tööstuse digitaliseerimisest, Arne Kaasik, 07.12.2016 TSENTERTööstuse digitaliseerimisest, Arne Kaasik, 07.12.2016 TSENTER
Tööstuse digitaliseerimisest, Arne Kaasik, 07.12.2016 TSENTER
 

Similar to C for Java programmers (part 2)

Ctutorial-Pointers 1.ppt
Ctutorial-Pointers 1.pptCtutorial-Pointers 1.ppt
Ctutorial-Pointers 1.ppt
DEEPAK948083
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 

Similar to C for Java programmers (part 2) (20)

C for Java programmers (part 3)
C for Java programmers (part 3)C for Java programmers (part 3)
C for Java programmers (part 3)
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
 
Ctutorial-Pointers 1.ppt
Ctutorial-Pointers 1.pptCtutorial-Pointers 1.ppt
Ctutorial-Pointers 1.ppt
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
SPL_PS2 (1).ppt
SPL_PS2 (1).pptSPL_PS2 (1).ppt
SPL_PS2 (1).ppt
 
C Pointers
C PointersC Pointers
C Pointers
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 

More from Dmitry Zinoviev

Network analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweetsNetwork analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweets
Dmitry Zinoviev
 

More from Dmitry Zinoviev (20)

Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)Machine Learning Basics for Dummies (no math!)
Machine Learning Basics for Dummies (no math!)
 
WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?WHat is star discourse in post-Soviet film journals?
WHat is star discourse in post-Soviet film journals?
 
The “Musk” Effect at Twitter
The “Musk” Effect at TwitterThe “Musk” Effect at Twitter
The “Musk” Effect at Twitter
 
Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?Are Twitter Networks of Regional Entrepreneurs Gendered?
Are Twitter Networks of Regional Entrepreneurs Gendered?
 
Using Complex Network Analysis for Periodization
Using Complex Network Analysis for PeriodizationUsing Complex Network Analysis for Periodization
Using Complex Network Analysis for Periodization
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Text analysis of The Book Club Play
Text analysis of The Book Club PlayText analysis of The Book Club Play
Text analysis of The Book Club Play
 
Exploring the History of Mental Stigma
Exploring the History of Mental StigmaExploring the History of Mental Stigma
Exploring the History of Mental Stigma
 
Roles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction NetworkRoles and Words in a massive NSSI-Related Interaction Network
Roles and Words in a massive NSSI-Related Interaction Network
 
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
 
Network analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweetsNetwork analysis of the 2016 USA presidential campaign tweets
Network analysis of the 2016 USA presidential campaign tweets
 
Network Analysis of The Shining
Network Analysis of The ShiningNetwork Analysis of The Shining
Network Analysis of The Shining
 
The Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network AnalysisThe Lord of the Ring. A Network Analysis
The Lord of the Ring. A Network Analysis
 
Pickling and CSV
Pickling and CSVPickling and CSV
Pickling and CSV
 
Python overview
Python overviewPython overview
Python overview
 
Welcome to CS310!
Welcome to CS310!Welcome to CS310!
Welcome to CS310!
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
The P4 of Networkacy
The P4 of NetworkacyThe P4 of Networkacy
The P4 of Networkacy
 
DaVinci Code. Network Analysis
DaVinci Code. Network AnalysisDaVinci Code. Network Analysis
DaVinci Code. Network Analysis
 
Introduction to Erlang Part 2
Introduction to Erlang Part 2Introduction to Erlang Part 2
Introduction to Erlang Part 2
 

Recently uploaded

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 

C for Java programmers (part 2)

  • 2. Heap & Pointers ● Types of storage: – global (defined in the static data segment) – automatic or local (defined in the program stack) – dynamic ● Dynamic memory blocks required by the program(mer) come from a memory pool called a heap—they are allocated and deallocated ● C does not have garbage collection. All allocated variables must be deallocated by the program(mer) ● A pointer is a variable whose value is a memory address representing the allocated memory block
  • 3. Declaring a Pointer ● Different types of pointers required for different data blocks: – int *p; /* An uninitialized pointer to an integer number or an array of integer numbers of size sizeof(int) */ – char *s; /* A pointer to a character array—a string (if NULL- terminated) */ – void *v; /* An unstructured uninitialized pointer—USE WITH CAUTION! */ – int *p1, *p2, p3; /* Two integer pointers and an integer */ – int **pp; /* A pointer to a pointer */ – double ***foo; /* A pointer to a pointer to a double pointer */ ● Types of pointers can be modified by casting: – int *p = …; – char *c = (char *)p; /* Now, c points to the first byte of the number! */ – c++; /* Now, it points to the second byte! */ ● Casting pointers should be avoided.
  • 4. Declaring a Pointer ● Different types of pointers required for different data blocks: – int *p; /* An uninitialized pointer to an integer number or an array of integer numbers of size sizeof(int) */ – int* p1; /* Where and whether you put the space, is up to you */ – char *s; /* A pointer to a character array—a string (if NULL- terminated) */ – void *v; /* An unstructured uninitialized pointer—USE WITH CAUTION! */ – int *p1, *p2, p3; /* Two integer pointers and an integer */ – int **pp; /* A pointer to an integer pointer */ – double ***foo; /* A pointer to a pointer to a double pointer */ ● Types of pointers can be modified by casting: – int *p = …; – char *c = (char *)p; /* Now, c points to the first byte of the number! */ – c++; /* Now, it points to the second byte! */ ● Casting pointers should be avoided.
  • 5. Initializing a Pointer ● The & operator calculates the address of a static or automatic variable: – int z = 0; – int *zp = &z; /* The address of z is now in zp */ – printf (“z=%i, &z=%xn”, z, zp); ● Remember that the address of an automatic variable makes no sense outside of the function: – int *foobar (void) { – int localVar = 617363; – int *ptr = &localVar; – return ptr; /* Bad idea! After foobar returns, localVar is no more!—Unless it's also static */ – }
  • 6. Dereferencing a Pointer ● To dereference a pointer is to obtain the value of the variable that it refers to. Operator * dereferences a pointer: – int var1 = 77, var2; – int *ptr = &var1; – var2 = *ptr; /* Now the value of var2 is 77 */ – (*ptr)++; /* Now, var1 is 78 */ – *ptr++; /* Dereference the pointer and then increment it; var1 is still 78, but ptr changed by 1 */ – (*ptr) = 10; /* Now, var1 is 10 */ ● Operators & and *, if properly used, are complementary: *&x is the same as x. However, &*x is not legal.
  • 7. “Constant” Pointers ● A pointer to a constant; – const int *p; /* p can change, but *p cannot */ – int const *p; /* same as above */ ● A constant pointer to a variable: – int *const p; /* *p can change, but p cannot */ ● A constant pointer to a constant: – const int *const p; /* nothing can change */
  • 8. Generic Pointers ● A generic pointer cannot be dereferenced: – void *generic = ….; – *generic = ... /* Illegal */ ● Any pointer can be safely cast to a generic pointer: – int var = 564; – int *iptr = &var; – void *generic = (void*)iptr; ● A generic pointer can be cast to a specific pointer of the original type, if known: – *(int*)generic; /* 564 */ ● What's a NULL? It's a macro defined in stdlib.h: – #define NULL (void*)0
  • 9. Pointer Arithmetic ● Operators +, -, ++, and – increment/decrement pointers by the number of object sizes: – char *s = …; – s++; /* s is incremented by 1 */ – – int *ptr = …; – ptr += 2; /* ptr is increased by 2*sizeof(int) */ ● Very useful to work with arrays in general and strings (NULL-terminated character arrays) in particular: – char *source = “Hello, world”; /* source is the address of the first element of the string */ – char *dest = …; /* allocate memory for the copy */ – while (*dest++ = *source++); /* copy while not NULL */ ● Pointers of the same type can be subtracted, and the difference is the number of objects between hgem: – int diff = ptr2 – ptr1; ● Pointers of the same type can be compared with >, >=, <, <=, ==, and !=. Comparing the pointers does not involve comparing the memory they point to.
  • 10. Memory Allocation ● Memory allocation functions are defined in stdlib.h. They return a pointer to a freshly allocated block or NULL in case of failure. ● Function void *malloc(size_t) gets a block of uninitialized memory. – int *myArray; – if (NULL == (myArray = malloc (32 * sizeof(int))) { – perror (“malloc”); – exit (EXIT_FAILURE); – } ● Function void *calloc(size_t,size_t) gets a block zero-filled memory. – if (NULL == (myArray = calloc (32, sizeof(int))) {... ● Function void *realloc(void*, size_t) changes the size of a previously allocated block and returns a new pointer, if necessary. The content of the block is preserved. – if (NULL == (myArray = realloc (myArray , 64 * sizeof(int))) {… ● If the return value is not saved, the allocated block is inaccessible (memory leak).
  • 11. Memory Deallocation ● Any previously allocated block must be deallocated with free(): – free (myArray); ● The value of myArray did not change, but should not be used anymore. For safety, nullify it: – myArray = NULL;
  • 12. Working with Memory Blocks ● memcpy() copies one block to another if they do not overlap ● memmove() copies one block to another; the blocks may overlap ● memcmp() compares two memory blocks, bytewise ● bzero() zero-fills a block
  • 13. The Mystery of scanf() ● All parameters to scanf, expect for the format string, must be pointers to the previously allocated storage variables: – int a; – double b; – char c; – char *str = malloc (128); – if (4 != scanf (“%i %lf %c %s”, &a, &b, &c, str)) {… /* str is already a pointer */
  • 14. The Mystery of FILE* ● FILE* is a pointer to a variable of type FILE, which is defined in stdio.h. In fact, the standard I/O streams are simply variables of this type: – FILE *stdin, *stdout, *stderr;
  • 15. Binary I/O ● Function long ftell(FILE*) returns the current reading/writing position in an open file. ● Function int fseek(FILE*, long offset, int mode) changes the current position in an open file by offset. The mode can be SEEK_SET (from the beginning of the file), SEEK_CUR (from the current position) or SEEK_END (from the end of the file). – fseek (f, sizeof (double), SEEK_CUR); /* go to the next double */ ● Function size_t fread(void *buff, size_t size, size_t count, FILE *f) reads size*count bytes into the previously allocated buffer buff from the previously open file f: – const int BUFF_SIZE = 1024; – FILE *infile = fopen(“myfile.txt”, “r”); /* check return value */ – char *data = malloc (BUFF_SIZE); /* check return value */ – if (BUFF_SIZE != fread (data, 1, BUFF_SIZE, infile)) {… ● Function size_t fwrite(void *buff, size_t size, size_t count, FILE *f) writes size*count bytes from the previously allocated buffer buff to the previously open file f. Both functions return the number of successfully read/written objects.
  • 16. Passing Arguments by Reference ● If you pass a pointer to an object to a function, the function can modify the object: – void addToInt (int *ptr, int change) { – (*ptr) += change; – } – ... – int val = 10; – addToInt (&val, 5); /* val is 15 now */ ● Always pass large objects (arrays and structs) by reference ● If the object shall not be modified, use a const pointer: – void functionThatShallNotChangeX (const int* x) { ... ● Pass small objects by reference only when the function shall change their value
  • 17. Pointers to Blocks of Pointers ● Memory-allocating functions can allocate memory for pointers to other blocks: – int **table; – table = malloc (sizeof (int*) * 100); /* a table of 100 integer pointers */ – for (i = 0; i < 100; i++) – table[i] = malloc (sizeof (int) * 256); /* each pointer, in turn, points to a block of 256 integers */ – – /* Did I tell you that C does to define variables only before the first executable statement of a function? */ – – int *q = table[0]; /* the address of the first block */ – int c = table[0][0]; /* the value at the beginning of the first block */