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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Dynamic memory allocation
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.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Pointers in C Rohit Khokher
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
C-strings Array with base type char One character per indexed variable
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Chapter 18 I/O in C.
Characters and Strings File Processing Exercise C Programming:Part 3.
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)
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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.
Today’s Material Strings Definition Representation Initialization
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Lecture 8 String 1. Concept of strings String and pointers
Chapter 18 I/O in C.
Plan for the Day: I/O (beyond scanf and printf)
Arrays in C.
CS111 Computer Programming
Programming in C Input / Output.
Programming in C Input / Output.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
EECE.2160 ECE Application Programming
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.
Programming in C Input / Output.
Chapter 18 I/O in C.
Presentation transcript:

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 that are not used in C++. C does not have the OOP features of C++, nor does it have as rich a library –no classes –I/O, string operations, and dynamic memory management done through library calls –Not much support for higher level data structures (e.g. STL) –Commonly lots of pointer manipulation

Topics Getting Started pointers character arrays and string functions structs I/O dynamic memory ( malloc and free )

Hello, World! #include int main() { printf(“Hello World\n”); return 0; } $ gcc -o hello hello.c $./hello Hello

Pointers To declare a pointer put * in front of the variable name. –int i; /* declare an int */ –int *ip; /* declare a pointer to an int */ –char *name; /* declare a pointer to */ /* a character */ Use & to get the address of a variable and * to dereference a pointer –ip = &i; /* assign the pointer variable */ /* ip the address of i */ –i = *ip; /* assign i the value of what */ /* ip points to. */

Pointers and Arrays Arrays are related to pointers. An array variable is a pointer to the first location in the array. –declare static character array of size 10 char name[10]; –can initialize character arrays char name[10] = “Fred”; –char *anotherName; –anotherName = Name; You can use pointer arithmetic to access array elements –access 4 th element of name name[4]; *(name + 4);

character arrays (strings) In C, there is no built-in support for strings. Instead strings are represented as null-terminated character arrays. char name[7]; name = “Fred” /* compiler adds ‘\0’ */ name[0] = ‘F’; name[1] = ‘r’; name[2] = ‘e’; name[3] = ‘d’; name[4] = ‘\0’ F r e d \0 name

Library Support for Strings #include strlen( const char *s ); –returns length of s (not including \0) int strcmp( const char *s1, const char *s2 ); –return 0 if s1 == s2, 0 if s1 > s2 strcat( char *dest, const char *src ); –appends src to the end of dest –char D[20]; D[0] = ‘\0’; –strcat(D,”Jeremy”); strcat(D,” “); strcat(D,”Johnson”); strncat( char *dest, const char *src, int n ) – appends upto n characters of src to the end of dest

Library Support for Strings char* strcpy( char *dest, const char *src ); –copy the string pointed to by src (including ‘\0’ ) to a character array pointed to by dest. –dest must already point to a character array with sufficient space to hold src. –no error checking for insufficient space char* strncpy( char *dest, const char *src, int n ); –copy at most n characters from the string pointed to by src to a character array pointed to by dest. –This should be used to prevent overflow errors.

structs A struct is used to group various data fields in a single type (classes without methods) typedef can be used to give a name to a particular struct declaration. Use “.” operator to access different fields. typedef struct Employee Employee; struct Employee { char *name; double wage; int id; } Employee worker; worker.name = “Fred”; worker.id = 1; worker.wage = 15.25;

Arrays of Arrays char *names[8]; names[0] = “start”; start\0 end middl e … … names

I/O #include stdin, stdout, stderr –standard input, standard output, and standard error file streams character I/O –int getchar() read a single character from stdin – if none available return EOF (end-of-file) getchar() is a macro that uses getc –int getc( FILE *FP ) read a single character from the file or stream identified by FP –int putchar( char c ) write the character c to stdout – if successful return the the character c otherwise EOF. –int putc( char c, FILE *FP ) write the character c to the file or stream identified by FP

mycat.c $ gcc mycat.c -o mycat $./mycat < mycat.c /* read character stream from stdin, copy to stdout */ #include int main() { int c; while ( (c = getchar()) != EOF ) putchar( (char)c ); return 0; }

Formatted Output printf prints a variable number of arguments using a specified format which is represented by a string –int printf( const char *FORMAT [, ARG,...]); –FORMAT is a string of characters (including special characters such as ‘\n’ for newline, and conversion formats for different types (with optional width and precision information). –man 3 printf # for more info –%d int –%c character –%s string –%f, %e, %g floating point number –%4.2f (4 indicates width, 2 precision, i.e. xx.xx) –%x hexadecimal int –%o octal int

Example #include int main() { typedef struct Employee Employee; struct Employee { char *name; double wage; int id; }; Employee worker; worker.name = "Fred"; worker.id = 1; worker.wage = 15.25; printf( "%s earns $%4.2f per hour\n", worker.name, worker.wage ); return 0; }

Example /* a program illustrating character arrays and pointer arithmetic */ #include int main() { char name[20] = "Fred"; char *anothername; anothername = name; printf( "name = %s\n",name ); printf( "Another name for %s is %s\n“, name, anothername ); printf( "The %d-th letter of %s = %c\n", strlen(name), name, name[3] ); printf( "The %d-th letter of %s = %c\n", strlen(name), name, *(name+3) ); return 0; }

Formatted Input scanf is used to read a variable number of arguments with input format specified by a fomat string similar to printf. –int scanf(const char *FORMAT [, ARG,...]); –The arguments to scanf are the addresses to the variables passed – this is required since the input variables will be modified –There must be sufficient arguments for the number of specified conversion types or unpredictable behavior may result –There must be sufficient space in the arguments (e.g. character arrays) to hold the input or unpredictable behavior may result

Example int main() { char name[MAXNAMELEN];/* fixed size array */ /* prompt the user to enter their name and read the string. */ /* "%s" tells scanf to read a string, which it stores in the array name. */ /* A string is read until whitespace is encountered. */ /* The address of the name must be passed to scanf. */ printf("Enter first name\n"); scanf("%s",name); printf("Hello %s\n",name); return 0; }

Dynamic Memory Allocation In C, dynamic memory is allocated through the use of a library routine called malloc. malloc inputs the desired amount of memory in bytes (use the sizeof macro to help determine the number of bytes needed) and returns a pointer (if successful) to the newly allocated memory. If unsuccessful, malloc returns NULL. The return type is void*, which is a generic pointer, since what the memory will be used for varies. A typecast should be used after calling malloc.

free and realloc When the memory allocated by malloc is no longer in use, it should be freed using free. –Not doing this causes a memory leak, which can cause problems when lots of memory is required. –freeing memory when it is still being used is a common bug; one that may be difficult to find. realloc can be used to obtain additional memory when the amount requested is insufficient (see grow from the text) –void *realloc( void *APTR, size_t NBYTES ); –void free( void *APTR );

Example (1/2) #include int main() { typedef struct Employee Employee; struct Employee { char*name; doublewage; intid; }; Employee *worker; /* allocate space for an Employee */ worker = (Employee *) malloc( sizeof( Employee )); /* check for NULL - see emalloc in the text. */ if (worker == NULL) { printf("malloc failed\n"); exit(1); }

Example (2/2) /* -> operator: dereference fields of a struct given a ptr to the struct */ worker->name = malloc( (strlen("Fred")+1) * sizeof(char) ); /* same as (*worker).name */ strcpy( worker->name, "Fred" ); worker->id = 1; worker->wage = 15.25; printf( "%s earns $%4.2f per hour\n", worker->name, worker->wage); /* free space allocated for worker */ free( worker->name ); free( worker ); return 0; } /* main */

Lists in C typedef struct Nameval Nameval; struct Nameval { char*name; intvalue; Nameval*next; /* in list */ }; /* newitem: create new item from name and value */ Nameval* newitem( char *name, int value ) { Nameval *newp; newp = (Nameval*) emalloc( sizeof( Nameval )); newp->name = name; newp->value = value; newp->next = NULL; return newp; }

Lists in C /* addfront: add newp to front of listp */ Nameval* addfront( Nameval *listp, Nameval *newp ) { newp->next=listp; return newp; } nvlist = addfront( nvlist, newitem( “smiley”, 0x263A ));

char** Again One must be careful when using multiple pointers to the same memory. –char name[10] = “Fred”; –char *anothername; –anothername = name; If name changes so does anothername. If you want a copy, allocate additional memory and copy ( strdup does this).

Example #include int main() { char name[20] = "Fred"; char *anothername; anothername = name; printf( "name = %s\n", name ); printf( "Another name for %s is %s\n", name, anothername ); name[3] = 'e'; printf( "name = %s\n", name); printf( "anothername has also changed to %s\n", anothername); /* the following causes problems since name and anothername point to the same space. */ free( anothername ); printf( "name = %s\n", name ); /* Bad! */ return 0; }

Command Line Arguments The main function can take optional arguments to provide access to the command line arguments when it is executed in a Unix environment. –int argc /* number of command line args*/ –char **args; /* an array of strings (character arrays) containing the name of the arguments. The 0 th element in args is the command – name of the executable file that contains the program. */

Example (1/2) /* generate a sequence of n random numbers in the range 1..u */ #include #define DEFLENGTH 10 #define DEFRANGE 1000 int main( int argc, char **argv ) { int n, u, i; n = DEFLENGTH; u = DEFRANGE;

Example (2/2) if (argc != 3) { printf( "usage: %s n u\n", argv[0] ); exit( 1 ); } n = atoi( argv[1] ); u = atoi( argv[2] ); for( i=0; i<n; i++ ) { printf( "NR == %d\n", (rand() % u) + 1 ); } return 0; }/* main */