SlideShare a Scribd company logo
C Tutorial - Pointers
CS 537 – Introduction to Operating Systems
The Stack
• The stack is the place where all local
variables are stored
– a local variable is declared in some scope
– Example
int x; // creates the variable x on the stack
• As soon as the scope ends, all local
variables declared in that scope end
– the variable name and its space are gone
– this happens implicitly – the user has no
control over it
The Heap
• The heap is an area of memory that the
user handles explicitly
– user requests and releases the memory
through system calls
– if a user forgets to release memory, it doesn’t
get destroyed
• it just uses up extra memory
• A user maintains a handle on memory
allocated in the heap with a pointer
Pointers
• A pointer is simply a local variable that
refers to a memory location on the heap
• Accessing the pointer, actually references
the memory on the heap
Basic Idea
pointer
(on the stack)
data
(on the heap)
1200
starting address
of data
1216
ending address
of data
1200
Declaring Pointers
• Declaring a pointer is easy
– declared like regular variable except that an asterisk
(*) is placed in front of the variable
– example
int *x;
– using this pointer now would be very dangerous
• x points to some random piece of data
– declaring a variable does not allocate space on the
heap for it
• it simply creates a local variable (on the stack) that will is a
pointer
• use malloc() to actually request memory on the heap
malloc
• Prototype: int malloc(int size);
– function searches heap for size contiguous free bytes
– function returns the address of the first byte
– programmers responsibility to not lose the pointer
– programmers responsibility to not write into area past
the last byte allocated
• Example:
Memory
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Key
previously allocated
new allocation
char *ptr;
ptr = malloc(4); // new allocation
ptr
10
free
• Prototype: int free(int ptr);
– releases the area pointed to by ptr
– ptr must not be null
• trying to free the same area twice will generate an error
• Example:
initial memory
0 1 2 3 4 5 6 7
Key
allocated memory
free memory
free(ptr);
p1
5
0 1 2 3 4 5 6 7
after free
p2
2
p2
2
p1
null
Using a Pointer
• To access a piece of data through a pointer,
place an asterisk (*) before the pointer
– example
char *ptr = malloc(1);
*ptr = ‘a’;
if(*ptr == ‘a’) { … }
• Using the pointer without the asterisk actually
accesses the pointer value
– not the data the pointer is referencing
– this is a very common mistake to make when trying to
access data
sizeof() Function
• The sizeof() function is used to determine
the size of any data type
– prototype: int sizeof(data type);
– returns how many bytes the data type needs
• for example: sizeof(int) = 4, sizeof(char) = 1
– works for standard data types and user
defined data types (structures)
Simple Example
int main() {
1 int x, y;
2 int *z;
3 z = malloc(sizeof(int));
4 y = 5;
5 *z = 3;
6 x = *z + y;
7 free(z);
return 0;
}
Stack
Heap
y
x
z
1
2
3
108
108
5
3
8
4
5
6
Simple Example
1. Declare local variables x and y.
2. Declare local pointer z.
3. Allocate space on the heap for single integer. This step also
makes z point to that location (notice the address of the space on
the heap is stored in z’s location on the stack.
4. Set the local variable y equal to 5.
5. Follow the pointer referenced by z to the heap and set that
location equal to 3.
6. Grab the value stored in the local variable y and follow the pointer
z to grab the value stored in the heap. Add these two together and
store the result in the local variable x.
7. Releases the memory on the heap (so another process can use it)
and sets the value in the z pointer variable equal to NULL. (this
step is not shown on the diagram)
Common Mistakes
• Using a pointer before allocating heap space
int *ptr;
*ptr = 5;
• Changing the pointer, not the value it references
int *ptr = malloc(sizeof(int));
ptr = 10; // sets value on stack to 10, not value on the heap
• Forgetting to free space on the heap (memory
leak)
int *p1 = malloc(sizeof(int));
int *p2 = malloc(sizeof(int));
p1 = p2; // making p1 point to p2 is fine, but now you can’t free
// the space originally allocated to p1
Learning to Use Pointers
• DRAW PICTURES
– when first using pointers it is much easier to
draw pictures to learn what is happening
– remember that an asterisk (*) follows the
pointer
– no asterisk (*) refers to the actual pointer
variable on the stack
One More Example
#include <stdio.h>
#define MAX_LINE 80
int main() {
char *str = malloc(MAX_LINE * sizeof(char));
printf(“Enter your name: “);
scanf(“%s”, str);
printf(“Your name is: %sn”, str);
free(str);
return 0;
}
1
2
3
str
23
23
. . .
0 1 2 3 78 79
Stack
Heap
1
2
P a t 0
One More Example
1. In one line, declare the pointer variable (gets
placed on the stack), allocate memory on the
heap, and set the value of the pointer variable
equal to the starting address on the heap.
2. Read a value from the user into the space on
the heap. This is why scanf takes pointers as
the parameters passed in.
3. Release all the space on the stack pointed to
by str and set the value of the str pointer on
the stack equal to null. (step not shown)
Dereferencing
• Pointers work because they deal with
addresses – not value
– an operator performs an action at the value
indicated by the pointer
– the value in the pointer is an address
• We can find the value of any variable by
dereferencing it
– simply put an ampersand (&) in front of the
variable and you now have the address of the
variable
Revisiting scanf()
• Prototype: int scanf(char* str, void*, void*, …);
• What is void*?
– void* is similar to object in Java
– it can point at anything
• Since the data types being passed into scanf
can be anything, we need to use void* pointers
• If you want to scan a value into a local variable,
you need to pass the address of that variable
– this is the reason for the ampersand (&) in front of the
variable
scanf() Example
#include <stdio.h>
#define MAX_LINE 80
int main() {
char *student = malloc(char * sizeof(char));
int grade;
printf(“Enter student’s name: “);
scanf(“%s”, student);
printf(“Enter student’s grade: “);
scanf(“%d”, &grade);
printf(“%s received a %dn”, student, grade);
free(student);
return 0;
}
1
2
3
4
5
scanf() Example
Stack
Heap
grade
student
2
3
5
100
4
100
. . .
0 1 2 3 78 79
P a t 0
1
scanf() Example
1. In one line, declare the pointer variable (gets
placed on the stack), allocate memory on the
heap, and set the value of the pointer variable
equal to the starting address on the heap.
2. Create the local variable grade on the heap.
3. Read a value from the user into the space on
the heap – beginning at the address indicated
by the pointer variable on the stack.
4. Read a value from the user into the address
referred to by the address of grade.
5. Release all the space on the stack pointed to
by student and set the value of the student
pointer on the stack equal to null. (step not
shown)
Pointers and Functions
• One limitation of functions is that they only
return a single value
• So how to change multiple values in a
single function?
– pass in pointers
– now any changes that are made are made to
the address being referred to
– this changes the value for the calling function
as well as the called function
#include <stdio.h>
void swap(float*, float*);
int main() {
float *f1, *f2;
f1 = malloc(sizeof(float));
f2 = malloc(sizeof(float));
printf(“Enter two numbers: “);
scanf(“%f%f”, f1, f2); // assume the user types 23 and 19
printf(“f1 = %ftf2 = %fn”, *f1, *f2);
swap(f1, f2);
printf(“After swap: f1 = %ftf2 = %fn”, *f1, *f2);
free(f1); free(f2);
return 0;
}
void swap(float* first, float* second) {
float tmp = *first;
*first = *second;
*second = tmp;
}
1
2
3
5
6
7
8
9
Example
Stack
Heap
f2
f1
232
100
3
main
second
first
232
100
swap
100
232
4
5
1
2
19
23
6
tmp
23
7
8
19
9
23
Example
1. Declare a pointer, f1, on stack.
2. Declare a pointer, f2, on stack.
3. Allocate space on the heap for a float and place the
address in the pointer variable f1.
4. Allocate space on the heap for a float and place the
address in the pointer variable f2.
5. Read values from the user. Hand scanf() the pointers
f1 and f2 and the data gets put on the heap.
6. Call the swap function. This pushes a new entry in the
stack. Copy the value of the pointers f1 and f2 into first
and second.
7. Create a new local variable tmp. Follow the pointer of
first and place its value into temp.
8. Follow the pointer of second, grab the value, follow the
pointer of first, place grabbed value there.
9. Grab the value from tmp, follow the pointer of second,
place the grabbed value there.
Lists
• Remember structures?
– structures together with pointers can be used
to make a list
• Some of the data in a structure will contain
the information being stored
• One of the fields in the structure will be a
pointer to the next structure in the list
Lists
• Example of a structure used in a linked list
struct list_node {
char letter;
struct list_node *next;
}
• The letter variable is the data to be stored
• The next variable will point at the next
element in the list
– or NULL if there are no more elements
Lists
struct list_node
letter
next
A
struct list_node
letter
next
M
struct list_node
letter
next
W
#include <stdio.h>
#include <string.h>
typedef struct list_node {
char word[20];
struct list_node* next;
} list_node;
int main() {
list_node* head = NULL;
char str[20];
printf(“Enter a word: “);
scanf(“%s”, str);
while(str[0] != ‘n’) {
list_node* tmp = (list_node*)malloc(sizeof(list_node));
strcpy(tmp->word, str);
if(head) { tmp->next = tmp; }
else { tmp->next = NULL; }
head = tmp;
printf(“Enter a word: “);
scanf(“%s”, str);
}
return 0;
}
Example
Stage 0: empty list
head
Stage 1: one element in list
struct list_node
word
next
hi
Stage 2: multiple elements in list
struct list_node
word
next
hi
struct list_node
word
next
at
head
head
2-D Pointers
• To really make things confusing, you can have
pointers to pointers
– and pointers to pointers to pointers …
• This comes in handy whenever a 2-D array is
needed
– you can also declare 2-D arrays, but these go on the
stack
– if dynamic memory is needed, must use pointers
• Declaring a pointer to a pointer
– just put 2 asterisks (*) in front of the variable
– example
char **names;
2-D Pointers
• Basic idea
twoD
100
2
0
3
1
4
100
230
400
23
450
600
argv
• Up until now, main has been written
– int main() { … }
• This is okay, but it’s usually written
– int main(int argc, char** argv) { … }
• argc
– number of command line arguments being passed in
• this counts the name of the program
• argv
– this is an array of strings – a 2-D character array
– each string represents one command line argument
Example
#include <stdio.h>
int main(int argc, char** argv) {
int i;
printf(“Number of arguments: %dn”, argc);
for(i=0; i<argc; i++)
printf(“argument %d: %s”, i, argv[i]);
return 0;
}
Example
• Given the following command line
prompt> example –o option required
• The output of the sample program
Number of arguments: 4
argument 0: example
argument 1: -o
argument 2: option
argument 3: required
Example
Stack
Heap
argv
argc
220
4
i
0
220
0
1
2
3
example
-o
option
required
100
335
678
120
Creating a 2-D Array
• Assume a 2-D array of characters is needed
– this is basically an array of strings
• Assume 4 strings with a max of 80 chars
int main() {
char** names;
int i;
names = (char**)malloc(4 * sizeof(char*));
for(i=0; i<4; i++)
names[i] = (char*)malloc(80 * sizeof(char));
for(i=0; i<4; i++)
free(names[i]);
free(names);
return 0;
}
1
2
3
4
5
6
2-D Arrays
• Once you really understand this previous
example, you are well on your way to
understanding pointers
• Let’s take a closer look at exactly what is
going on
2-D Arrays
Stack
Heap
names
220
220
0
1
2
3
100
335
678
120
i
0
X 1 2 3
X X X
80 chars wide
1
3
2
4
2-D Arrays
1. Create a pointer on the stack that will point to a
group of pointers
2. Create a local variable on the stack
3. Make names point to an array of 5 pointers to
characters. This array is located on the heap.
4. Go through each pointer in the array and make
it point at an 80 character array. Each of these
80 character arrays is also located on the heap
5. Freeing each of the 80 character arrays. (not
shown on diagram).
6. Free the array of pointers. (not shown on the
diagram)

More Related Content

Similar to Ctutorial-Pointers 1.ppt

Pointers
PointersPointers
Pointers
Frijo Francis
 
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
Rai University
 
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
Rai University
 
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
sumitbardhan
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
ShivamChaturvedi67
 
Pointer
PointerPointer
Pointer
manish840
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
ngonidzashemutsipa
 
Pointer
PointerPointer
Chapter09-10 Pointers and operations .PPT
Chapter09-10  Pointers and operations .PPTChapter09-10  Pointers and operations .PPT
Chapter09-10 Pointers and operations .PPT
ShalabhMishra10
 
Chapter09-10.PPT
Chapter09-10.PPTChapter09-10.PPT
Chapter09-10.PPT
shubhamshukla9769280
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
sangeeta borde
 
Session 5
Session 5Session 5
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
ambikavenkatesh2
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
1. C Basics for Data Structures Bridge Course
1. C Basics for Data Structures   Bridge Course1. C Basics for Data Structures   Bridge Course
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
C language
C languageC language
C language
Robo India
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)
Dmitry Zinoviev
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
Mohamed Fawzy
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
jack881
 

Similar to Ctutorial-Pointers 1.ppt (20)

Pointers
PointersPointers
Pointers
 
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
 
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
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Pointer
PointerPointer
Pointer
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Pointer
PointerPointer
Pointer
 
Chapter09-10 Pointers and operations .PPT
Chapter09-10  Pointers and operations .PPTChapter09-10  Pointers and operations .PPT
Chapter09-10 Pointers and operations .PPT
 
Chapter09-10.PPT
Chapter09-10.PPTChapter09-10.PPT
Chapter09-10.PPT
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Session 5
Session 5Session 5
Session 5
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
1. C Basics for Data Structures Bridge Course
1. C Basics for Data Structures   Bridge Course1. C Basics for Data Structures   Bridge Course
1. C Basics for Data Structures Bridge Course
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
C language
C languageC language
C language
 
C for Java programmers (part 2)
C for Java programmers (part 2)C for Java programmers (part 2)
C for Java programmers (part 2)
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 

More from DEEPAK948083

turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.pptturban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
DEEPAK948083
 
introAdhocRoutingRoutingRoutingRouting-new.ppt
introAdhocRoutingRoutingRoutingRouting-new.pptintroAdhocRoutingRoutingRoutingRouting-new.ppt
introAdhocRoutingRoutingRoutingRouting-new.ppt
DEEPAK948083
 
SensorSensorSensorSensorSensorSensor.ppt
SensorSensorSensorSensorSensorSensor.pptSensorSensorSensorSensorSensorSensor.ppt
SensorSensorSensorSensorSensorSensor.ppt
DEEPAK948083
 
Chapter1_IntroductionIntroductionIntroduction.ppt
Chapter1_IntroductionIntroductionIntroduction.pptChapter1_IntroductionIntroductionIntroduction.ppt
Chapter1_IntroductionIntroductionIntroduction.ppt
DEEPAK948083
 
introDMintroDMintroDMintroDMintroDMintroDM.ppt
introDMintroDMintroDMintroDMintroDMintroDM.pptintroDMintroDMintroDMintroDMintroDMintroDM.ppt
introDMintroDMintroDMintroDMintroDMintroDM.ppt
DEEPAK948083
 
lect1lect1lect1lect1lect1lect1lect1lect1.ppt
lect1lect1lect1lect1lect1lect1lect1lect1.pptlect1lect1lect1lect1lect1lect1lect1lect1.ppt
lect1lect1lect1lect1lect1lect1lect1lect1.ppt
DEEPAK948083
 
Chchchchchchchchchchchchchchchchc 11.pptx
Chchchchchchchchchchchchchchchchc 11.pptxChchchchchchchchchchchchchchchchc 11.pptx
Chchchchchchchchchchchchchchchchc 11.pptx
DEEPAK948083
 
applicationapplicationapplicationapplication.ppt
applicationapplicationapplicationapplication.pptapplicationapplicationapplicationapplication.ppt
applicationapplicationapplicationapplication.ppt
DEEPAK948083
 
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITYMOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
DEEPAK948083
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
DEEPAK948083
 
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
DEEPAK948083
 
Lect no 13 ECC.ppt
Lect no 13 ECC.pptLect no 13 ECC.ppt
Lect no 13 ECC.ppt
DEEPAK948083
 
block ciphermodes of operation.pptx
block ciphermodes of operation.pptxblock ciphermodes of operation.pptx
block ciphermodes of operation.pptx
DEEPAK948083
 
Lect no 13 ECC.ppt
Lect no 13 ECC.pptLect no 13 ECC.ppt
Lect no 13 ECC.ppt
DEEPAK948083
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptx
DEEPAK948083
 
whitman_ch04.ppt
whitman_ch04.pptwhitman_ch04.ppt
whitman_ch04.ppt
DEEPAK948083
 
lesson333.ppt
lesson333.pptlesson333.ppt
lesson333.ppt
DEEPAK948083
 
ICS PPT Unit 4.ppt
ICS PPT Unit 4.pptICS PPT Unit 4.ppt
ICS PPT Unit 4.ppt
DEEPAK948083
 
stack-Intro.pptx
stack-Intro.pptxstack-Intro.pptx
stack-Intro.pptx
DEEPAK948083
 
BST.ppt
BST.pptBST.ppt
BST.ppt
DEEPAK948083
 

More from DEEPAK948083 (20)

turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.pptturban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
turban_ch07ch07ch07ch07ch07ch07dss9e_ch07.ppt
 
introAdhocRoutingRoutingRoutingRouting-new.ppt
introAdhocRoutingRoutingRoutingRouting-new.pptintroAdhocRoutingRoutingRoutingRouting-new.ppt
introAdhocRoutingRoutingRoutingRouting-new.ppt
 
SensorSensorSensorSensorSensorSensor.ppt
SensorSensorSensorSensorSensorSensor.pptSensorSensorSensorSensorSensorSensor.ppt
SensorSensorSensorSensorSensorSensor.ppt
 
Chapter1_IntroductionIntroductionIntroduction.ppt
Chapter1_IntroductionIntroductionIntroduction.pptChapter1_IntroductionIntroductionIntroduction.ppt
Chapter1_IntroductionIntroductionIntroduction.ppt
 
introDMintroDMintroDMintroDMintroDMintroDM.ppt
introDMintroDMintroDMintroDMintroDMintroDM.pptintroDMintroDMintroDMintroDMintroDMintroDM.ppt
introDMintroDMintroDMintroDMintroDMintroDM.ppt
 
lect1lect1lect1lect1lect1lect1lect1lect1.ppt
lect1lect1lect1lect1lect1lect1lect1lect1.pptlect1lect1lect1lect1lect1lect1lect1lect1.ppt
lect1lect1lect1lect1lect1lect1lect1lect1.ppt
 
Chchchchchchchchchchchchchchchchc 11.pptx
Chchchchchchchchchchchchchchchchc 11.pptxChchchchchchchchchchchchchchchchc 11.pptx
Chchchchchchchchchchchchchchchchc 11.pptx
 
applicationapplicationapplicationapplication.ppt
applicationapplicationapplicationapplication.pptapplicationapplicationapplicationapplication.ppt
applicationapplicationapplicationapplication.ppt
 
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITYMOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
MOBILE & WIRELESS SECURITY And MOBILE & WIRELESS SECURITY
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
5virusandmaliciouscodechapter5-130716024935-phpapp02-converted.pptx
 
Lect no 13 ECC.ppt
Lect no 13 ECC.pptLect no 13 ECC.ppt
Lect no 13 ECC.ppt
 
block ciphermodes of operation.pptx
block ciphermodes of operation.pptxblock ciphermodes of operation.pptx
block ciphermodes of operation.pptx
 
Lect no 13 ECC.ppt
Lect no 13 ECC.pptLect no 13 ECC.ppt
Lect no 13 ECC.ppt
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptx
 
whitman_ch04.ppt
whitman_ch04.pptwhitman_ch04.ppt
whitman_ch04.ppt
 
lesson333.ppt
lesson333.pptlesson333.ppt
lesson333.ppt
 
ICS PPT Unit 4.ppt
ICS PPT Unit 4.pptICS PPT Unit 4.ppt
ICS PPT Unit 4.ppt
 
stack-Intro.pptx
stack-Intro.pptxstack-Intro.pptx
stack-Intro.pptx
 
BST.ppt
BST.pptBST.ppt
BST.ppt
 

Recently uploaded

欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
arcosarturo900
 
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
g1inbfro
 
Charging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
Charging and Fueling Infrastructure Grant: Round 2 by Brandt HertensteinCharging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
Charging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
Forth
 
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
ramaysha335
 
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
utuvvas
 
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
ggany
 
User Manual Alfa-Romeo-MiTo-2014-UK-.pdf
User Manual Alfa-Romeo-MiTo-2014-UK-.pdfUser Manual Alfa-Romeo-MiTo-2014-UK-.pdf
User Manual Alfa-Romeo-MiTo-2014-UK-.pdf
militarud
 
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
andagarcia212
 
Dahua Security Camera System Guide esetia
Dahua Security Camera System Guide esetiaDahua Security Camera System Guide esetia
Dahua Security Camera System Guide esetia
Esentia Systems
 
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
ggany
 
Top-Quality AC Service for Mini Cooper Optimal Cooling Performance
Top-Quality AC Service for Mini Cooper Optimal Cooling PerformanceTop-Quality AC Service for Mini Cooper Optimal Cooling Performance
Top-Quality AC Service for Mini Cooper Optimal Cooling Performance
Motor Haus
 
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
cenaws
 
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
pycfbo
 
gHSM Product Introduction 2022newdocumane.pdf
gHSM Product Introduction 2022newdocumane.pdfgHSM Product Introduction 2022newdocumane.pdf
gHSM Product Introduction 2022newdocumane.pdf
maicuongdt21
 
Kenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
Kenwood DDX71/491/471/371/3108/30718/271/2071 User ManualKenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
Kenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
derekmelino
 
Charging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
Charging Fueling & Infrastructure (CFI) Program Resources by Cat PleinCharging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
Charging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
Forth
 
Cargdor frontal volvo L180E para trabajar en carga de rocas.
Cargdor frontal volvo L180E para trabajar en carga de rocas.Cargdor frontal volvo L180E para trabajar en carga de rocas.
Cargdor frontal volvo L180E para trabajar en carga de rocas.
Eloy Soto Gomez
 
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
asjpkomrxo
 
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
utuvvas
 
Charging Fueling & Infrastructure (CFI) Program by Kevin Miller
Charging Fueling & Infrastructure (CFI) Program  by Kevin MillerCharging Fueling & Infrastructure (CFI) Program  by Kevin Miller
Charging Fueling & Infrastructure (CFI) Program by Kevin Miller
Forth
 

Recently uploaded (20)

欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
欧洲杯竞猜-欧洲杯竞猜下注平台-欧洲杯竞猜投注平台|【​网址​🎉ac44.net🎉​】
 
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
原版制作(澳洲WSU毕业证书)西悉尼大学毕业证文凭证书一模一样
 
Charging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
Charging and Fueling Infrastructure Grant: Round 2 by Brandt HertensteinCharging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
Charging and Fueling Infrastructure Grant: Round 2 by Brandt Hertenstein
 
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
欧洲杯竞猜-欧洲杯竞猜外围竞猜-欧洲杯竞猜竞猜平台|【​网址​🎉ac123.net🎉​】
 
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
原版定做(mmu学位证书)英国曼彻斯特城市大学毕业证本科文凭原版一模一样
 
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
按照学校原版(UTS文凭证书)悉尼科技大学毕业证快速办理
 
User Manual Alfa-Romeo-MiTo-2014-UK-.pdf
User Manual Alfa-Romeo-MiTo-2014-UK-.pdfUser Manual Alfa-Romeo-MiTo-2014-UK-.pdf
User Manual Alfa-Romeo-MiTo-2014-UK-.pdf
 
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
美洲杯押注靠谱的软件-美洲杯押注靠谱的软件推荐-美洲杯押注靠谱的软件|【​网址​🎉ac123.net🎉​】
 
Dahua Security Camera System Guide esetia
Dahua Security Camera System Guide esetiaDahua Security Camera System Guide esetia
Dahua Security Camera System Guide esetia
 
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
按照学校原版(UniSA文凭证书)南澳大学毕业证快速办理
 
Top-Quality AC Service for Mini Cooper Optimal Cooling Performance
Top-Quality AC Service for Mini Cooper Optimal Cooling PerformanceTop-Quality AC Service for Mini Cooper Optimal Cooling Performance
Top-Quality AC Service for Mini Cooper Optimal Cooling Performance
 
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
一比一原版悉尼大学毕业证(USYD毕业证书)学历如何办理
 
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
一比一原版南昆士兰大学毕业证(USQ毕业证书)学历如何办理
 
gHSM Product Introduction 2022newdocumane.pdf
gHSM Product Introduction 2022newdocumane.pdfgHSM Product Introduction 2022newdocumane.pdf
gHSM Product Introduction 2022newdocumane.pdf
 
Kenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
Kenwood DDX71/491/471/371/3108/30718/271/2071 User ManualKenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
Kenwood DDX71/491/471/371/3108/30718/271/2071 User Manual
 
Charging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
Charging Fueling & Infrastructure (CFI) Program Resources by Cat PleinCharging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
Charging Fueling & Infrastructure (CFI) Program Resources by Cat Plein
 
Cargdor frontal volvo L180E para trabajar en carga de rocas.
Cargdor frontal volvo L180E para trabajar en carga de rocas.Cargdor frontal volvo L180E para trabajar en carga de rocas.
Cargdor frontal volvo L180E para trabajar en carga de rocas.
 
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
欧洲杯下注-欧洲杯下注下注app-欧洲杯下注盘口app|【​网址​🎉ac22.net🎉​】
 
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
定制(london学位证书)英国伦敦大学毕业证本科学历原版一模一样
 
Charging Fueling & Infrastructure (CFI) Program by Kevin Miller
Charging Fueling & Infrastructure (CFI) Program  by Kevin MillerCharging Fueling & Infrastructure (CFI) Program  by Kevin Miller
Charging Fueling & Infrastructure (CFI) Program by Kevin Miller
 

Ctutorial-Pointers 1.ppt

  • 1. C Tutorial - Pointers CS 537 – Introduction to Operating Systems
  • 2. The Stack • The stack is the place where all local variables are stored – a local variable is declared in some scope – Example int x; // creates the variable x on the stack • As soon as the scope ends, all local variables declared in that scope end – the variable name and its space are gone – this happens implicitly – the user has no control over it
  • 3. The Heap • The heap is an area of memory that the user handles explicitly – user requests and releases the memory through system calls – if a user forgets to release memory, it doesn’t get destroyed • it just uses up extra memory • A user maintains a handle on memory allocated in the heap with a pointer
  • 4. Pointers • A pointer is simply a local variable that refers to a memory location on the heap • Accessing the pointer, actually references the memory on the heap
  • 5. Basic Idea pointer (on the stack) data (on the heap) 1200 starting address of data 1216 ending address of data 1200
  • 6. Declaring Pointers • Declaring a pointer is easy – declared like regular variable except that an asterisk (*) is placed in front of the variable – example int *x; – using this pointer now would be very dangerous • x points to some random piece of data – declaring a variable does not allocate space on the heap for it • it simply creates a local variable (on the stack) that will is a pointer • use malloc() to actually request memory on the heap
  • 7. malloc • Prototype: int malloc(int size); – function searches heap for size contiguous free bytes – function returns the address of the first byte – programmers responsibility to not lose the pointer – programmers responsibility to not write into area past the last byte allocated • Example: Memory 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Key previously allocated new allocation char *ptr; ptr = malloc(4); // new allocation ptr 10
  • 8. free • Prototype: int free(int ptr); – releases the area pointed to by ptr – ptr must not be null • trying to free the same area twice will generate an error • Example: initial memory 0 1 2 3 4 5 6 7 Key allocated memory free memory free(ptr); p1 5 0 1 2 3 4 5 6 7 after free p2 2 p2 2 p1 null
  • 9. Using a Pointer • To access a piece of data through a pointer, place an asterisk (*) before the pointer – example char *ptr = malloc(1); *ptr = ‘a’; if(*ptr == ‘a’) { … } • Using the pointer without the asterisk actually accesses the pointer value – not the data the pointer is referencing – this is a very common mistake to make when trying to access data
  • 10. sizeof() Function • The sizeof() function is used to determine the size of any data type – prototype: int sizeof(data type); – returns how many bytes the data type needs • for example: sizeof(int) = 4, sizeof(char) = 1 – works for standard data types and user defined data types (structures)
  • 11. Simple Example int main() { 1 int x, y; 2 int *z; 3 z = malloc(sizeof(int)); 4 y = 5; 5 *z = 3; 6 x = *z + y; 7 free(z); return 0; } Stack Heap y x z 1 2 3 108 108 5 3 8 4 5 6
  • 12. Simple Example 1. Declare local variables x and y. 2. Declare local pointer z. 3. Allocate space on the heap for single integer. This step also makes z point to that location (notice the address of the space on the heap is stored in z’s location on the stack. 4. Set the local variable y equal to 5. 5. Follow the pointer referenced by z to the heap and set that location equal to 3. 6. Grab the value stored in the local variable y and follow the pointer z to grab the value stored in the heap. Add these two together and store the result in the local variable x. 7. Releases the memory on the heap (so another process can use it) and sets the value in the z pointer variable equal to NULL. (this step is not shown on the diagram)
  • 13. Common Mistakes • Using a pointer before allocating heap space int *ptr; *ptr = 5; • Changing the pointer, not the value it references int *ptr = malloc(sizeof(int)); ptr = 10; // sets value on stack to 10, not value on the heap • Forgetting to free space on the heap (memory leak) int *p1 = malloc(sizeof(int)); int *p2 = malloc(sizeof(int)); p1 = p2; // making p1 point to p2 is fine, but now you can’t free // the space originally allocated to p1
  • 14. Learning to Use Pointers • DRAW PICTURES – when first using pointers it is much easier to draw pictures to learn what is happening – remember that an asterisk (*) follows the pointer – no asterisk (*) refers to the actual pointer variable on the stack
  • 15. One More Example #include <stdio.h> #define MAX_LINE 80 int main() { char *str = malloc(MAX_LINE * sizeof(char)); printf(“Enter your name: “); scanf(“%s”, str); printf(“Your name is: %sn”, str); free(str); return 0; } 1 2 3 str 23 23 . . . 0 1 2 3 78 79 Stack Heap 1 2 P a t 0
  • 16. One More Example 1. In one line, declare the pointer variable (gets placed on the stack), allocate memory on the heap, and set the value of the pointer variable equal to the starting address on the heap. 2. Read a value from the user into the space on the heap. This is why scanf takes pointers as the parameters passed in. 3. Release all the space on the stack pointed to by str and set the value of the str pointer on the stack equal to null. (step not shown)
  • 17. Dereferencing • Pointers work because they deal with addresses – not value – an operator performs an action at the value indicated by the pointer – the value in the pointer is an address • We can find the value of any variable by dereferencing it – simply put an ampersand (&) in front of the variable and you now have the address of the variable
  • 18. Revisiting scanf() • Prototype: int scanf(char* str, void*, void*, …); • What is void*? – void* is similar to object in Java – it can point at anything • Since the data types being passed into scanf can be anything, we need to use void* pointers • If you want to scan a value into a local variable, you need to pass the address of that variable – this is the reason for the ampersand (&) in front of the variable
  • 19. scanf() Example #include <stdio.h> #define MAX_LINE 80 int main() { char *student = malloc(char * sizeof(char)); int grade; printf(“Enter student’s name: “); scanf(“%s”, student); printf(“Enter student’s grade: “); scanf(“%d”, &grade); printf(“%s received a %dn”, student, grade); free(student); return 0; } 1 2 3 4 5
  • 21. scanf() Example 1. In one line, declare the pointer variable (gets placed on the stack), allocate memory on the heap, and set the value of the pointer variable equal to the starting address on the heap. 2. Create the local variable grade on the heap. 3. Read a value from the user into the space on the heap – beginning at the address indicated by the pointer variable on the stack. 4. Read a value from the user into the address referred to by the address of grade. 5. Release all the space on the stack pointed to by student and set the value of the student pointer on the stack equal to null. (step not shown)
  • 22. Pointers and Functions • One limitation of functions is that they only return a single value • So how to change multiple values in a single function? – pass in pointers – now any changes that are made are made to the address being referred to – this changes the value for the calling function as well as the called function
  • 23. #include <stdio.h> void swap(float*, float*); int main() { float *f1, *f2; f1 = malloc(sizeof(float)); f2 = malloc(sizeof(float)); printf(“Enter two numbers: “); scanf(“%f%f”, f1, f2); // assume the user types 23 and 19 printf(“f1 = %ftf2 = %fn”, *f1, *f2); swap(f1, f2); printf(“After swap: f1 = %ftf2 = %fn”, *f1, *f2); free(f1); free(f2); return 0; } void swap(float* first, float* second) { float tmp = *first; *first = *second; *second = tmp; } 1 2 3 5 6 7 8 9
  • 25. Example 1. Declare a pointer, f1, on stack. 2. Declare a pointer, f2, on stack. 3. Allocate space on the heap for a float and place the address in the pointer variable f1. 4. Allocate space on the heap for a float and place the address in the pointer variable f2. 5. Read values from the user. Hand scanf() the pointers f1 and f2 and the data gets put on the heap. 6. Call the swap function. This pushes a new entry in the stack. Copy the value of the pointers f1 and f2 into first and second. 7. Create a new local variable tmp. Follow the pointer of first and place its value into temp. 8. Follow the pointer of second, grab the value, follow the pointer of first, place grabbed value there. 9. Grab the value from tmp, follow the pointer of second, place the grabbed value there.
  • 26. Lists • Remember structures? – structures together with pointers can be used to make a list • Some of the data in a structure will contain the information being stored • One of the fields in the structure will be a pointer to the next structure in the list
  • 27. Lists • Example of a structure used in a linked list struct list_node { char letter; struct list_node *next; } • The letter variable is the data to be stored • The next variable will point at the next element in the list – or NULL if there are no more elements
  • 29. #include <stdio.h> #include <string.h> typedef struct list_node { char word[20]; struct list_node* next; } list_node; int main() { list_node* head = NULL; char str[20]; printf(“Enter a word: “); scanf(“%s”, str); while(str[0] != ‘n’) { list_node* tmp = (list_node*)malloc(sizeof(list_node)); strcpy(tmp->word, str); if(head) { tmp->next = tmp; } else { tmp->next = NULL; } head = tmp; printf(“Enter a word: “); scanf(“%s”, str); } return 0; }
  • 30. Example Stage 0: empty list head Stage 1: one element in list struct list_node word next hi Stage 2: multiple elements in list struct list_node word next hi struct list_node word next at head head
  • 31. 2-D Pointers • To really make things confusing, you can have pointers to pointers – and pointers to pointers to pointers … • This comes in handy whenever a 2-D array is needed – you can also declare 2-D arrays, but these go on the stack – if dynamic memory is needed, must use pointers • Declaring a pointer to a pointer – just put 2 asterisks (*) in front of the variable – example char **names;
  • 32. 2-D Pointers • Basic idea twoD 100 2 0 3 1 4 100 230 400 23 450 600
  • 33. argv • Up until now, main has been written – int main() { … } • This is okay, but it’s usually written – int main(int argc, char** argv) { … } • argc – number of command line arguments being passed in • this counts the name of the program • argv – this is an array of strings – a 2-D character array – each string represents one command line argument
  • 34. Example #include <stdio.h> int main(int argc, char** argv) { int i; printf(“Number of arguments: %dn”, argc); for(i=0; i<argc; i++) printf(“argument %d: %s”, i, argv[i]); return 0; }
  • 35. Example • Given the following command line prompt> example –o option required • The output of the sample program Number of arguments: 4 argument 0: example argument 1: -o argument 2: option argument 3: required
  • 37. Creating a 2-D Array • Assume a 2-D array of characters is needed – this is basically an array of strings • Assume 4 strings with a max of 80 chars int main() { char** names; int i; names = (char**)malloc(4 * sizeof(char*)); for(i=0; i<4; i++) names[i] = (char*)malloc(80 * sizeof(char)); for(i=0; i<4; i++) free(names[i]); free(names); return 0; } 1 2 3 4 5 6
  • 38. 2-D Arrays • Once you really understand this previous example, you are well on your way to understanding pointers • Let’s take a closer look at exactly what is going on
  • 40. 2-D Arrays 1. Create a pointer on the stack that will point to a group of pointers 2. Create a local variable on the stack 3. Make names point to an array of 5 pointers to characters. This array is located on the heap. 4. Go through each pointer in the array and make it point at an 80 character array. Each of these 80 character arrays is also located on the heap 5. Freeing each of the 80 character arrays. (not shown on diagram). 6. Free the array of pointers. (not shown on the diagram)