C Pointers 2013 Author Riko H i

Similar documents
Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Intro. Scheme Basics. scm> 5 5. scm>

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

C++ for Java Programmers

Programming and Data Structure

5 R1 The one green in the same place so either of these could be green.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

(Refer Slide Time: 01.26)

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

6 Stephanie Well. It s six, because there s six towers.

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

9 R1 Get another piece of paper. We re going to have fun keeping track of (inaudible). Um How much time do you have? Are you getting tired?

Lecture Transcript While and Do While Statements in C++

Pointers in C/C++ 1 Memory Addresses 2

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

2.4 Choose method names carefully

First of all, it is a variable, just like other variables you studied

Pointers, Arrays and Parameters

(Refer Slide Time 6:48)

Win-Back Campaign- Re-Engagement Series

Introduction to Access 97/2000

Combinatorics Prof. Dr. L. Sunil Chandran Department of Computer Science and Automation Indian Institute of Science, Bangalore

Yup, left blank on purpose. You can use it to draw whatever you want :-)

Computer Architecture Prof. Mainak Chaudhuri Department of Computer Science & Engineering Indian Institute of Technology, Kanpur

CMSC202 Computer Science II for Majors

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

Spectroscopic Analysis: Peak Detector

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Module 6. Campaign Layering

Grade Point Scales Standard Honors AP/College A B C D F Sample file

What Are CSS and DHTML?

Usability Test Report: Requesting Library Material 1

VLOOKUP() takes three mandatory parameters and one default/optional parameter:

(Refer Slide Time: 02.06)

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

Boolean Expressions. Is Equal and Is Not Equal

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Boolean Expressions. Is Equal and Is Not Equal

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Skill 1: Multiplying Polynomials

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Programming and Data Structures Prof. N. S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras

It s possible to get your inbox to zero and keep it there, even if you get hundreds of s a day.

SPRITES Moving Two At the Same Using Game State

Out for Shopping-Understanding Linear Data Structures English

Computer Science 210: Data Structures

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

1.7 Limit of a Function

(Refer Slide Time: 01:25)

COPYRIGHTED MATERIAL. Starting Strong with Visual C# 2005 Express Edition

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

The Stack, Free Store, and Global Namespace

C++ for Java Programmers

T H E I N T E R A C T I V E S H E L L

If Statements, For Loops, Functions

2016 All Rights Reserved

hp calculators HP 17bII+ Registers / Memory Banks The Stack Registers The Storage Registers

CIO 24/7 Podcast: Tapping into Accenture s rich content with a new search capability

6.001 Notes: Section 15.1

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

A Beginner s Guide to Successful Marketing

MITOCW watch?v=0jljzrnhwoi

GSAK (Geocaching Swiss Army Knife) GEOCACHING SOFTWARE ADVANCED KLASS GSAK by C3GPS & Major134

CS125 : Introduction to Computer Science. Lecture Notes #11 Procedural Composition and Abstraction. c 2005, 2004 Jason Zych

UV Mapping to avoid texture flaws and enable proper shading

(Refer Slide Time: 06:01)

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Section 0.3 The Order of Operations

Compiler Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Here are a couple of warnings to my students who may be here to get a copy of what happened on a day that you missed.

Robert Ragan s TOP 3

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lutheran High North Technology The Finder

CS 4349 Lecture August 21st, 2017

(Refer Slide Time 01:41 min)

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Decisions, Decisions. Testing, testing C H A P T E R 7

CSE / ENGR 142 Programming I

Chapter 1 Getting Started

Google Analytics 101

At the end of this module, the student should be able to:

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Lecture 19 CSE August You taught me Language, and my profit on t is I know how to curse. William Shakspere, The Tempest, I, ii.

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

Second Examination Solution

Lastly, in case you don t already know this, and don t have Excel on your computers, you can get it for free through IT s website under software.

Preprocessor Directives

Transcription:

http:/cdorm.net/understanding C Pointers 2013 Author Riko H i

Copyright 2013 CDorm.net All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, without the prior written permission of the publisher. Disclaimer All the material contained in this book is provided for educational and informational purposes only. No responsibility can be taken for any results or outcomes resulting from the use of this material. While every attempt has been made to provide information that is both accurate and effective, the author does not assume any responsibility for the accuracy or use/misuse of this information. http:/cdorm.net/understanding C Pointers 2013 Author Riko H ii

Acknowledgements I would like to thank my father who kept pushing and encouraging me to make this book, for believing I have what it takes to make it real and helping to make this project possible, taking it from an idea to a realized e-book. Thank you, for without you this would not be possible. http:/cdorm.net/understanding C Pointers 2013 Author Riko H iii

Table of Contents Chapter 1: C Pointers Basic Concept... 1-2 Chapter 2: Using Pointers in C... 3-8 Chapter 3: Arrays... 9-10 Chapter 4: Functions and Function Argument... 11-15 http:/cdorm.net/understanding C Pointers 2013 Author Riko H iv

Chapter 1: C Pointers basic concepts Welcome to the world of pointers! If you are reading this then that means you probably have some trouble with pointers or maybe just want some extra information on the topic. Let s begin! If we are planning to dive into this vast world we first need to talk about a couple things. For starters we must understand what exactly a pointer is and how does it function in principle. You might be tempted to or have already searched the internet high and low for a quick, simple and easy definition of a pointer and came up with something like: a pointer is a programming language data type whose value refers directly to another value stored elsewhere in the computer memory using its address. It might then go into referencing registers and using all kinds of complicated analogies to explain the concept leaving you more confused than when you started reading. Now, time for that simple explanation you were waiting for. The first question anyone may ask is: What is a pointer and how do they work? Well, a pointer in programming is simply a reference to an actual variable. How do they work? I shall explain the concept two ways: First, let s imagine we have a mailman, some mail and a house for the mail to be delivered. We can look at the data as the mail, the variable as the house and the pointer as the mailman. What does a mailman do? You guessed it! Deliver! If you have a package to be delivered (i.e. data to be stored) you give the address of the house to the mailman, then you give the mailman the package, however, you expect that if you access/look into the house you would see the package. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 1

Similarly, when you use pointers to manipulate data you give data to the pointer but when the variable it is referencing is accessed it too shall have the data because the pointer (just like the mailman) is the gateway to the variable. If that concept didn t clear up anything for you let s look at it another way: Let s say we have a funnel, a marble and a bottle. The bottle is our variable, the marble our data and the funnel as our pointer. If we were to insert the funnel to our bottle and put the marble in the funnel what would you expect to happen? The marble would fall in the bottle. What if you look through the funnel or look directly in the bottle, what would you see? The marble. Similarly, when you use pointers to manipulate data you give data to the pointer but when the variable it is referencing is accessed it too shall have the data because the pointer (just like the funnel) is the gateway to the variable. If it sounds trivial or really simple that s because it isn t complicated once you have the right imagination. This brings up a really important point about pointers (no pun intended). As with the second analogy, you ll notice that the data (marble) is actually in the variable (bottle) and not in the pointer (funnel) itself. That s because pointers don t actually store data, they just tell the data where to go. That s really it guys, that s how simple the concept of a pointer is. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 2

Chapter 2: Using pointers in C Now that we understand how a pointer works let s get into using them because it s no use just knowing how being able to visualize how they work we have to be able to use them at our will. Declaring First, how do you declare a pointer? In C, the asterisk denotes a pointer. (type *variable) NB: the type of the pointer must match the type of data you plan to reference. float *p; This is a pointer float x; This is NOT a pointer. It s as simple as that. Using pointers After declaring but before you can start using a pointer, you must reference a variable (give the mailman the address of the house. This is done by using the & operation. p = &x; Notice when assigning address asterisk isn t used Only after assignment can manipulation can begin. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 3

Example #include <stdio.h> int main (void) { int *ptr; /*DECLARING POINTER*/ int x; ptr = &x; /*ASSIGNING POINTER TO X VARIABLE*/ *ptr = 5; printf(" %d ", *ptr); /*PRINTING POINTER*/ x = 3; printf(" %d ", x); /*PRINTING VARIABLE*/ printf(" %d ", *ptr); /*PRINTING POINTER*/ return (0); } What is the output of this program? Continue reading to find out! http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 4

The output would be: We only set the pointer value to 5 once, do you understand why 3 occurred when we printed the pointer a second time? Remember the funnel and marble analogy? Lets recall that a pointer is simply a funnel connected to our variable so even though we didn t directly drop a 3 in the pointer we did drop it in the varibale ( x = 3; ) so when we looked in the funnel the second time we simply saw that 3. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 5

Let s try one more: #include <stdio.h> int main (void) { int *ptr1; int *ptr2; int x,y; ptr1 = &x; *ptr1 = 3; ptr2 = &y; y = 2; printf(" %d ", *ptr1 + *ptr2); printf(" %d ", x + y); printf(" %d ", x + *ptr1); ptr1 = &y; x = 10; printf(" %d ", *ptr1 + *ptr2); return (0);} What s the output this time? Take your time and check the next page when you ve got your answers! http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 6

Output: Let s look into this one in detail: Let Line 1 be int *ptr1; Lines 1-3 are standard declaration commands. Line 4 connects the first pointer (*ptr1) to x. Line 5 then sends the number 3 to x via ptr1 Line 6 is the same as Line 4 this time assigning ptr2 to y. Instead of going via the pointer (*ptr2), Line 7 directly inserts 2 into y. Now comes the complicated part: printf(" %d ", *ptr1 + *ptr2); *ptr1 is simply x and *ptr2 is simply y therefore this line is printing x + y which is 3 + 2 which is 5. Next, printf(" %d ", x + y); x + y is the same as *ptr1 + *ptr2 because ptr1 is referencing x and ptr2 is referencing y and we established from before to be 5. printf(" %d ", x + *ptr1); *ptr1 is pointing to x so x + *ptr1 is simply x + x which is 6. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 7

What do the next two lines do? ptr1 = &y; is nothing new to us by now all this is doing to taking the funnel out of bottle X and placing it in bottle Y. Therefore the line printf(" %d ", *ptr1 + *ptr2); simply prints the value of *ptr1 + *ptr2 which is the same as y + y since both pointers are now pointing towards the same variable y. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 8

Chapter 3: Arrays Now that we had covered pointers and are now ready to tackle problems involving them let s shift our attention and focus to another area in programming known as Arrays. Simple data types use a single cell to store a variable. As we dive into the world of programming we will see it is more efficient to group data items together than to give each variable its own cell. This group is called an array. Declaring and using an Array and its cells Declaring an array is as simple as declaring any other thing in C. We simply use the format: type variable[size] int my_array[3]; This says I want three integer variable for my using. If you are curious like I am you may be wondering where are the 3; they are: my_array[0] Notice that we start from 0 my_array[1] my_array[2]. We now have access to these three variables to do with what we wish simply by declaring the array. These cells can now be treated as normal variables and can be manipulated as such. This comes in handy in cases where you have lots of data to store. For instance is you have 900 numbers to store would rather have to declare 900 variables or would you rather type float numbers[900]; There are also extremely fast and efficient ways to fill and use arrays which we will get into in a later issue. Imagine filling all 900 of those slots with one line of code (hint: loops). http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 9

Example: #include <stdio.h> int main (void) { int my_array[3]; my_array[1] = 7; my_array[2] = 4; my_array[0] = my_array[1] - my_array[2]; printf( " %d ", my_array[0] ); printf( " %d ", my_array[1] ); printf( " %d ", my_array[2] ); return (0); } What s the output? http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 10

Chapter 4: Functions and Function Arguments Pointers? Check. Arrays? Check. Now that we have a clear understand on those, time to move on to Functions and Function Arguments. A function is nothing more than a program within a program. A dedicated set of code which when called upon carries out the objective of its code, this could be anything from an addition function which when called adds 4 numbers then multiplies it by 2 or a factorial function which when called takes and displays the factorial of a given number. It could even be a function which when called does nothing. The possibilities are endless when it comes to function because just like how they are trillions of programs that can be coded they are trillions of functions. Why? Because they ARE programs and you, the coder, decide what they do and how they do it. With that said, all I can do is show you how to set it up and you and your imagination and expertise learnt from this e-book and elsewhere can fill the inside with whatever you want! Declaring a function Declaring a function is not like declaring a pointer or array. As matter of fact, they aren t even declared in the same place. Declaring a function goes like this: #include <stdio.h> type name(arguments) We shall discuss arguments later. { /*FUNCTION CODE GOES HERE* } int main() {. return(0); } http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 11

Types of functions Value functions These functions give back a value when called and therefore need to be stored when called. e.g. int addition (int num1,int num2) { return(num1+num2); } e.g. float multiply (int num1, int num2) { int x=2; return (num1*num2*x); } Void functions These functions return nothing and therefore do not need to be stored when called e.g. void print() { printf ( This function does nothing other than print this message ) } Notice there is no return command. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 12

Using a function After we declare a function along with the code of what it s going to do we now have to use it. Using a function is referred to as calling it and it is done in the main program and it is as simple and easy as calling a taxi. To call a value function we must first have a variable (must be same date type as function and is declared the standard way) to store the output of this function (i.e. the function is giving us something so we must have somewhere to put it). x = addition (4, 2); we have just called our addition function and the result shall be stored in x. For void functions, because it is not giving anything, we do not need to put it anywhere and can just call by typing its name: print(); Function Arguments Arguments is just a fancy word for inputs. So function arguments just means function inputs. As in, what data do you need (if any) from the main program for your function to operate? For instance if we were to make an addition function that adds two numbers, logically we would need the two numbers to add so our function arguments for example would be (int num1, int num2). They are declared in the heading of the function and do not need to be re-declared in the body. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 13

Example #include <stdio.h> int add (int x, int y) { return (x+y); } void print() { printf("our first void function! "); } int main (void) { int result; print(); printf("i wonder what is 2+3? "); result = add(2,3); printf(" %d ",result); return (0); } Can you tell me what the output is? Be careful! Let s see on the next page. http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 14

Output Well folks, That s it basically Understanding C Pointers in a nutshell. I hope you like this book and I know it will be a little pocket guide to C Programming and I will be putting out some more short reports like this one to help struggling Student because I know I was there once. Shoot me an email riko@cdorm.net or visit the site for more in the future. Until then. :>) http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 15

Personal Message from Riko: I hope you find this ebook useful and that it helps you to create your own highly successful C programs! Feel free to check out my website and see the free video and share the link with anyone who might be interested. Free Video: http://cdorm.net For more free training on C Programming visit my website: http://cdorm.net click here http:/cdorm.net/understanding C Pointers 2013 Author Riko H Page 16