Day 04 Introduction to C.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Chapter 7 Process Environment Chien-Chung Shen CIS, UD
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Informationsteknologi Tuesday, September 18, 2007 Computer Systems/Operating Systems - Class 61 Today’s class Finish review of C Process description and.
CS 414/415 section C for Java programmers Indranil Gupta.
Copyright©1998 Angus Wu PROGRAMMING METHDOLODGY AND SOFTWARE ENGINEERING EE PROGRAMMING METHODOLOGY AND SOFTWARE ENGINEERING.
1 CSSE 332 Standard Library, Storage classes, and Make.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
1 More on pointers. Example 1 – pass by value/reference int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int.
Software Engineering Recitation 9 Suhit Gupta. Today C.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
1 Day 01 Introduction to C. Saving Dyknow notes Save on the server. Can access from anywhere. Will have to install Dyknow on that machine. Must connect.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Why learn C (after Java)? Both high-level and low-level language Better control of low-level mechanisms Performance better than Java Java hides many details.
Outline Midterm results Static variables Memory model
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
(language, compilation and debugging) David 09/16/2011.
1 Functions  A function is a named, independent section of C++ code that performs a specific task and optionally returns a value to the calling program.
CSCI 171 Presentation 6 Functions and Variable Scope.
1 CSC2100B Data Structure Tutorial 1 Online Judge and C.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Dynamic memory allocation and Intraprogram Communication.
Day 01 Introduction to C.
Angela Dalton (based on original slides by Indranil Gupta)
Pointers verses Variables
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Function: Declaration
C Primer.
Day 03 Introduction to C.
Functions and Structured Programming
Day 02 Introduction to C.
Day 03 Introduction to C.
C programming language
Command-Line Arguments
2-D arrays a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32
Programmazione I a.a. 2017/2018.
Instructor: Ioannis A. Vetsikas
Dynamic memory allocation and Intraprogram Communication
CSC 253 Lecture 8.
Dynamic memory allocation and Intraprogram Communication
Programming and Data Structures
CSC 253 Lecture 8.
Programming in C Pointer Basics.
Programming in C Miscellaneous Topics.
Outline Defining and using Pointers Operations on pointers
Programming in C Pointer Basics.
Programming in C Miscellaneous Topics.
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Introduction to Computer Organization & Systems
7. Pointers, Dynamic Memory
In C Programming Language
Chapter 11 Programming in C
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Arrays, Pointers, and Strings
Programming in C Pointer Basics.
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Day 04 Introduction to C

Functions – pointers as arguments #include <stdio.h> int SumAndInc(int *pa, int *pb,int* pc); int main(int argc, char *argv[]) { int a=4, b=5, c=6; int *ptr = &b; int total = SumAndInc(&a,ptr,&c); /* call to the function */ printf(“The sum of 4 and 5 is %d and c is %p\n”,total,c); } SumAndInc(int *pa, int *pb,int *pc ){/* pointers as arguments */ *pc = *pc+1; /* return a pointee value */ /*NOT *(pc+1)*/ return (*pa+*pb); /* return by value */

In main() a 4 4000 b 5 4004 c 6 4008 ptr 4004 4012 pa 4000 6000 pb 4004 6004 pc 4008 6008 In function

In main() after the function call 4 4000 b 5 4004 c 7 4008 ptr 4004 4012 In main() after the function call

What’s wrong with this ? #include <stdio.h> void DoSomething(int *ptr); int main(int argc, char *argv[]) { int *p; DoSomething(p); printf(“%d”, *p); /* will this work ? */ return 0; } void DoSomething(int *ptr){ /* passed and returned by reference */ int temp= 5+3; ptr = &(temp); /* compiles correctly, but gives incorrect output */

p ? 4000 In main() ptr 6000 temp 6004 In the function ? 8 6004

p ? 4000 In main() after the function call

Functions: Pass by value int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int b){ int c; c = a + b; return c; } a b c 4000 4004 4008 p q r 5 6 2000 2004 2008 5 7 12 12

Problem 2 – pass pointer by value int main(){ int *x,*y; int p = 5; int q = 6; x = &p; y = &q; Sum_1(p, y); return 0; } void Sum_1(int a, int *b){ int input; printf(“Enter an integer:”); scanf("%d", &input); *b = a + input; } Example15.c 5 2012 2008 2012 a b input 4000 4004 4008 x y p q 5 2000 2004 2008 2012 15 6 20

Functions - Passing and returning arrays #include <stdio.h> void init_array( int array[], int size ) ; int main(int argc, char *argv[] ) { int list[5]; init_array( list, 5); for (i = 0; i < 5; i++) printf(“next:%d”, list[i]); } void init_array(int array[], int size) { /* why size ? */ /* arrays ALWAYS passed by reference */ int i; for (i = 0; i < size; i++) array[i] = 0;

Passing/Returning a structure /* pass struct by value */ void DisplayYear_1( struct birthday mybday ) { printf(“I was born in %d\n”, mybday.year); } /* - inefficient: why ? */ /* pass pointer to struct */ void DisplayYear_2( struct birthday *pmybday ) { printf(“I was born in %d\n”, pmybday->year); /* Note: ‘->’, not ‘.’, after a struct pointer*/ } /* return struct by value */ struct birthday GetBday(void){ struct birthday newbday; newbday.year=1971; /* ‘.’ after a struct */ return newbday; } /* - also inefficient: why ? */

Example: Array and pointer Statically allocated data int a[5]; int *p; int i = 0; for(i=0; i < 5; i++) a[i] = 3 + i; p= a; p = (int *)malloc(3 * sizeof(int)); a[0] a[1] a[2] a[3] a[4] p 2000 2004 2008 2012 2016 2020 3 4 5 6 7 2000 8000 p[0] p[1] p[2] 8000 8004 8008 Heap (space for dynamically allocated data)

Problem 3: pointer to a struct void print_student_age_1(Student any){ printf("Age is %d\n", any.age); any.gpa = 2.0; } void print_student_age_2(Student * any){ printf("Age is %d\n", any->age); any->gpa = 2.0; void print_student_age_3(const Student * any){ int main(){ Student john; Student * john_ptr = &john; john.age = 20; john.gpa = 3.5; print_student_age_1(john); printf("gpa is %.1f\n", john.gpa); print_student_age_2(john_ptr); return 0; } any.age any.gpa 20 4000 4008 Example16.c 3.5 2.0 john.age john.gpa john_ptr 20 2000 2004 2008 3.5 2.0 any 2000 4000

Problem 4: malloc and structs Student * many = (Student *)malloc(3 * sizeof(Student)); many[0].age = 20; many[0].gpa = 3.5; //void print_student_info( Student class [ ], int count ); OR //void print_student_info( Student * class, int count ); print_student_info(___________________, 3 ); Example17.c many 8000 2000 many[0].age many[0].gpa many[1].age many[1].gpa many[2].age many[2].gpa 23 3.4 22 3.6 21 4.0 8000 8004 8008 8012 8016 8020

Input/Output statements fprintf(stdout,”….”,…); - buffered output Equivalent to printf(“….”,…) fscanf(stdin,…); Equivalent to scanf(…) fprintf(stderr,”…”,…); - un-buffered output Use for error messages. perror(…); Use to print messages when system calls fail.

Storage classes Allocate memory only when function is executed Automatic (default for local variables) Allocate memory only when function is executed e.g. auto int i; Register Direct compiler to place variable in a register e.g. register counter = 1; Static Allocate memory as soon as program execution begins Scope is local to the function that declares the variable. Value is retained and space is de-allocated only when program (not function) quits. e.g. static int i;

Storage classes - contd Extern Default for function names. For a variable shared by two or more files: int i; //global variable in file 1 extern int i; //global in files 2,3 … x For a function shared by 2 or more files, place a function prototype at the beginning of the files.

Program with multiple files #include <stdio.h> #include “mypgm.h” void Myproc() { int mydata=g_data * 2; . . . /* some code */ } #include <stdio.h> #include “mypgm.h” int g_data=5; int main() { Myproc(); return 0; } mypgm.c main.c main.c Library headers Standard User-defined void Myproc(); extern int g_data; mypgm.h

To compile gcc main.c mypgm.c –o run or gcc main.c –c -o main.o gcc mypgm.c –c -o mypgm.o gcc mypgm.o main.o –o run Can also use a makefile.

enum - enumerated data types #include <stdio.h> enum month{ JANUARY, /* like #define JANUARY 0 */ FEBRUARY, /* like #define FEBRUARY 1 */ MARCH /* … */ }; In main: enum month birthMonth; If(birthMonth = = JANUARY){…} /* alternatively, …. */ JANUARY=1, /* like #define JANUARY 1 */ MARCH=3, /* like #define MARCH 3 */ FEBRUARY=2, /* … */ Note: if you use the #define, the value of JANUARY will not be visible in the debugger. An enumerated data type’s value will be.

Before you go…. Always initialize anything before using it (especially pointers) Don’t use pointers after freeing them Don’t return a function’s local variables by reference No exceptions – so check for errors everywhere An array is also a pointer, but its value is immutable.