University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Lecture 20 Arrays and Strings
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
MPI and C-Language Seminars Seminar Plan (1/3)  Aim: Introduce the ‘C’ Programming Language.  Plan to cover: Basic C, and programming techniques.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
GUIDED BY- A.S.MODI MADE BY- 1. SHWETA ALWANI 2. PRIYANKA.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
File IO and command line input CSE 2451 Rong Shi.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Homework HW6 On line – due next class Starting K&R Chapter 7 and Appendix B Also, UNIX – Various chapters in Glass.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C is a high level language (HLL)
CSC 2400 Computer Systems I Lecture 6 Strings. 2 Characters The char type is an 8-bit byte containing ASCII code values (e.g., ‘A’ = 65, ‘B’ = 66,...)
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
ECE Application Programming
CSE 451 C refresher.
A bit of C programming Lecture 3 Uli Raich.
C Programming Tutorial – Part I
Command Line Arguments
File Access (7.5) CSE 2031 Fall July 2018.
Introduction to C CSE 2031 Fall /3/ :33 AM.
C Basics.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C EECS May 2019.
Chapter 1 c++ structure C++ Input / Output
Pointers, Dynamic Data, and Reference Types
SPL – PS1 Introduction to C++.
C Tutorial Adapted from Wei Qian’s C tutorial slides.
Introduction to C CS 3410.
Presentation transcript:

University of Calgary – CPSC 441

C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function  Compile output: executable file. Running the executable (default name a.out) starts main function  Typically, single program with all user code linked in – but can be dynamic libraries (.dll,.so) JAVA PROGRAM  Collection of classes  Class containing main method is starting class  Compile output: jar file. Running “java StartClass” invokes StartClass.main method  JVM loads other classes as required C++ is C extended with object oriented functionality (and more!) 2

// C #include int main(int argc, char *argv[])) { printf("Hello world!\n"); return 0; } // C++ #include using namespace std; int main(int argc, char *argv[]) { cout << "Hello world!" << endl; return 0; } 3

 gcc is a driver which calls the preprocessor, compiler (cc1 or cc1plus), assembler, and linker as needed $ gcc hello.c $ a.out Hello, World! $ gcc hello.c –o hello $./hello Hello, World! 4

Some useful command line options:  [-o file]: specifies the output file for object or executable  [-Wall]: show all warnings (highly recommended)  [-l libnam]: Links the library libname e.g., -lsocket  If you get errors saying the library cannot be found, make sure the path is correctly set, and you do have the libraries you need. 5

 Demo 1. Write code 2. Compile 3. Run 6

int main(int argc, char *argv[])  argc : number of arguments passed to the program  argv : array of strings showing command line arguments  Name of executable + space-separated arguments  Name of executable is stored in argv[0]  The return value is int  convention: 0 means success, > 0 some error 7

8

NameDescriptionSize (Bytes)Range char Character or small integer.Typically 1 signed: -128 to 127 unsigned: 0 to 255 short int (short) Short Integer.>=2 signed: to unsigned: 0 to int Integer. Most efficient. >=2; Typically 4 signed: to unsigned: 0 to long int (long) Long integer.>=4 signed: to unsigned: 0 to long long int long long integer.>=8 signed: -9.2e18 to 9.2e18 unsigned: -1.8e19 to 1.8e19 float Floating point number.4+/- 3.4e +/- 38 (~7 digits) double Double precision floating point number. 8+/- 1.8e +/- 308 (~15 digits) long double Long double precision floating point number. >=8; Typically 16+/- 1.2e +/ (~34 digits) 9

10

 Array declaration (on the stack): int a[];  C/C++ arrays have no length attribute!  Note: when passing an array to a function, typically you have to pass the array size as a separate argument as well.  You have to take care of array bounds yourself  This code could compile and run, but most likely, you’ll see unexpected behavior or crash your program.  Array’s name is a pointer to its first element int input[10]; input[10] = 20; // out of bound! input[-1] = 5; // out of bound! 11

 C struct is a way to logically group related types  Is very similar to (but not same as) C++/java classes  Is somehow a class without methods  Members are always public (no encapsulation concept in c)  A struct component can be of any type (including other struct types), but cannot be recursive, unless it is a pointer to itself struct address { char* street; char* city; char* zip; }; typedef struct { char* name; unsigned int ID; struct address Address; } student_item; struct link_list { student_item student_info; struct link_list *next; }; typedef struct link_list student; 12

 A pointer is just an address to some memory location.  Another variable  Some dynamically allocated memory  Some function  NULL &x (address of x) 4 int *p = &x; int x = 4; Address of allocated memory int *p = malloc (sizeof int); ? allocated memory 13

 Declaration: using “ * ” symbol before variable name. int * ptr = NULL; //creates pointer for integer  Allocation: allocate new memory to a pointer using the keyword malloc in C ( new in C++) int *p = malloc(sizeof(int)); int *p = (int *) malloc(10 * sizeof (int)); // array of int  Deallocation: clear the allocated memory when you are done using it. Otherwise, you have memory leak!!! free(p);  Dereferencing: accessing data from the pointer x = *p;  Referencing: getting the memory location for the data p = &x; 14

 In C, a string is an array of char terminated with “\0” (a null terminator: ‘\0’)  “hello” is hello\0  Declaring and initializing a string: 15 // strings in stack space char str1[10]; // a string of 10 characters char str2[10] = {"hello"}; // initialized string char *strp1; // a char pointer // string in heap space // a char pointer initialized to point to a chunk of memory. char *strp2 = malloc(sizeof(char)*10);

#include Functions:  char *strcpy(char *dest, char *source)  copies chars from source array into dest array up to NULL  char *strncpy(char *dest, char *source, int num)  copies chars; stops after num chars if no NULL before that; appends NULL  int strlen(const char *source)  returns number of chars, excluding NULL  char *strchr(const char *source, const char ch)  returns pointer to first occurrence of ch in source; NULL if none  char *strstr(const char *source, const char *search)  return pointer to first occurrence of search in source 16

 int sscanf(char *string, char *format,...)  parse the contents of string according to format  return the number of successful conversions  int sprintf(char *buffer, char *format,...)  produce a string formatted according to format directives and place this string into the buffer  return number of successful conversions 17

CodeMeaningVariabl e %c Matches a single character char %d Matches an integer in decimal int %f Matches a real number float %s Matches a string up to a white space char * %[^c] Matches a string up to next c char char * 18 For many more formatting options, refer to:

CodeMeaningVariable %nc%nc Char in field of n spaces char %nd%nd Integer in field of n spaces int %n.mf Real number in width n.m decimals float, double %n.ms First m chars from string in width n char * % Writes a single % to the stream 19 For many more formatting options, refer to: Values normally right-justified; use negative field width to get left-justified

#include  Formatted I/O int scanf(const char *format,...)  read from standard input and store according to format. int printf(const char *format,...)  write to standard output according to format  File I/O: FILE * FILE *fopen(const char *path, const char *mode)  open a file and return the file descriptor int fclose(FILE *stream)  close the file; return 0 if successful, EOF if not 20

#include  Other I/O operations: int getchar()  read the next character from stdin; returns EOF if none char *fgets(char *buf, int size, FILE *in)  read the next line from a file into buf int fputs(const char *str, FILE *out)  output the string to a file, stopping at ‘\0’  returns number of characters written or EOF 21

 Sample C program:  Input: list of grades of student homework  Output: The computed final marks 22

 C for Java programmers:  C tutorial:  Socket programming with C: (for next session)  Beej's Guide to Network Programming Using Internet Sockets