Array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }

Slides:



Advertisements
Similar presentations
#include void main() { float x = 1.66, y = 1.75; printf(%f%f,ceil(x), floor(y)); }
Advertisements

Buffer Overflows Nick Feamster CS 6262 Spring 2009 (credit to Vitaly S. from UT for slides)
Introduction to C Programming
C’ POINTERS Basic&Examples. Q:what’s the output? int array[] = { 45, 67, 89 }; int *array_ptr = array; printf(" first element: %i\n", *(array_ptr++));
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
 A string is an array of characters.  Strings must have a 0 or null character after the last character to show where the string ends.  The null character.
Strings string.h library. String Library Functions Dr. Sadık EşmelioğluCENG 1142 NameDescription strlen return the length of string not counting \0 strcopy.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Pseudocode A way to make programming easier Start with a verbal description of what the program is supposed to do! Slowly transform it into C, defining.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
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.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Chapter Fourteen Strings Revisited. Strings A string is an array of characters A string is a pointer to a sequence of characters A string is a complete.
Sort the given string, without using string handling functions.
Senem KUMOVA METİN CS FALL 1 ARRAYS && SORTING && STRINGS CHAPTER 6 cont.
By Senem Kumova Metin 1 POINTERS + ARRAYS + STRINGS REVIEW.
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Tuesday, January 23, 2007 "We can't solve problems by using the same kind of thinking we used when we created them." -Albert Einstein.
1 Strings ( מחרוזות ). 2 Agenda Definition and initialization Termination Input / Output String library.
Character Arrays strlen("hello, world"); /* string constant */ strlen(array); /* char array[100]; */ strlen(ptr); /* char *ptr; */ char pmessage[] = "now.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
CS Nov 2006 C-strings.
Exercise 10 Review: pointers, strings and recursion.
Tutorial #8 Summer strings #include int main() { char str1[] = {‘h’,’e’,’l’,’l’,’o’}; char str[] = {‘h’,’e’,’l’,’l’,’o’,’\0’}; char p[] = ”hello”;
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Introduction to C programming
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Strlen() implementation /* strlen : return length of string s */ int strlen(char *s) { int n; for (n = 0 ; s[n] != ‘\0’ ; n++) ; return n; } /* strlen.
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)
Xuan Guo Review for the Final Exam Xuan Guo July 29 8:30AM – 10:30AM Classroom South 300 CSC
String functions+ string I.Mona Alshehri. String Functions: Header file:#include Function: Int strlen(char s[n]) Description Calculates the length of.
EXERCISE Arrays, structs and file processing. Question You own a pet store. You want to keep an inventory of all the pets that you have. Pets available.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
1 MIPS Assembly Language Programming CDA 3101 Discussion Section 04.
COP 3275 – Character Strings and Introduction to Pointers Instructor: Diego Rivera-Gutierrez.
C vs. C++ I/O Declaration Placement Strings Minor syntax differences (ala enum)
Pointers and Arrays An array's name is a constant whose value is the address of the array's first element. For this reason, the value of an array's name.
CMSC 104, Version 8/061L25Strings.ppt Strings Topics String Libraries String Operations Sample Program Reading Sections
Department of Electronic & Electrical Engineering IO reading and writing variables scanf printf format strings "%d %c %f"
Pointer Lecture 2 Course Name: High Level Programming Language Year : 2010.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
 Learn how to form strings using one-dimensional array  String manipulation functions:  strcpy  strrev  strcmp  Program using strings.
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
DATA PROCESSING Gary Sham 15/1/2011. Data Processing  Data Processing ≠ Algorithm  Data Processing:  Get the input so that we can use it in our program.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Lecture 8 String 1. Concept of strings String and pointers
Strings (מחרוזות).
Exercises on String Operations
INC 161 , CPE 100 Computer Programming
Character Arrays char string1[] = “first”;
Programming Strings.
Introduction to Problem Solving and Programming
Presentation transcript:

array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }

Pointer arithmetic strcpy void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Exercise Write a program that gets a string from the user and checks whether or not it is a palindrome Example for a palindrome: abbcbba (Hint: use strlen…)

Palindrome.c /* This program checks whether a given string is a palindrome*/ #include int main(void) { int len,i; char str[101]; printf("Enter a string\n"); scanf("%100s",str); len = strlen(str); for (i=0; i<len/2; i++) if (str[i] != str[len-i-1]) { printf("The string is not a palindrome!\n"); return 0; } printf("The string is a palindrome!\n"); return 0; }

An additional use for pointers A function that accepts an array and searches for something within it (a char, a number, etc.) What should the function return? The index where the ‘something’ was found A pointer to the place where it was found

Functions that return pointers Like any other data type, functions can return pointers For example, a prototype for a function returning a pointer to char will be – char *func(…); But how would we indicate failure Suppose we searched the array and didn’t find anything – what should we return?

strchr – pointer arithmetic char *my_strchr(char str[], char c) { char *search = str; while (*search != '\0') { if (*search == c) return search; search++; } return NULL; } ‘h’‘e’‘l’ ‘o’ str ‘\0’ c ‘l’ search

Mystery – what does this do? int main(void) { char s[LENGTH+1]; char *p; scanf("%100s", s); p = strchr(s, ','); while(p!=NULL) { *p = ' '; p = strchr(p+1, ','); } printf("The result is - %s\n", s); return 0; }

Exercise Implement the string.h function strrchr that returns a pointer to the last occurrence of a character inside a string. Write a program that accepts a string and char from the user, displays what remains of the string after the last occurrence of that char

Solution strrchr.c

strncmp Declared in string.h, with prototype int strncmp(char *s1, char *s2, int n); Returns 0 if the first n letters of s1 are equal to those of s2 Returns non-zero if first n letters are different

Exercise Using strncmp, implement the following function – Input – two strings str1, str2 Output – a pointer to the first instance of str2 in str1, or NULL Write a program that accepts two strings from the user and reports whether the first contains the second

solution strstr.c

Last one Implement the following function – Input – two strings str1, str2 Output – pointer to the first instance in str1 of any of the characters contained in Write a program that accepts a string from the user and replaces all punctuation signs (,.;:!?) with spaces

solution strcspn.c

Some functions of string.h Implementations of two string.h functions: strcpy.c – copies one string into the other strchr.c – returns a pointer to the first occurrence of a character within a string strstr.c – returns a pointer to the first occurrence of one string within another strcspn.c – returns a pointer to the first occurrence of a single char from one string in the second

Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables This size can’t be changed after compilation However, we don’t always know in advance how much space we would need for an array or a variable We would like to be able to dynamically allocate memory

The malloc function void *malloc(unsigned int nBytes); The function malloc is used to dynamically allocate nBytes worth of space How to determine nBytes? malloc returns a pointer to the allocated area on success, NULL on failure You should always check whether memory was successfully allocated Remember to #include

Example dynamic_reverse_array.c

Why casting? The casting in y=(int *) malloc(n*sizeof (int)); is needed because malloc returns void * : void *malloc(unsigned int nbytes); The type void * specifies a general pointer, which can be cast to any pointer type.

What is this ‘sizeof’ ? The sizeof operator gets a variable or a type as an input and outputs its size in bytes: double x; s1=sizeof(x); /* s1 is 8 */ s2=sizeof(int) /* s2 is 4 */

Free the allocated memory segment void free(void *ptr); We use free(p) to free the allocated memory pointed to by p If p doesn’t point to an area allocated by malloc, a run-time error occurs Always remember to free the allocated memory once you don’t need it anymore Otherwise, you may run out of memory before you know it!

Another example another_strcpy.c

Exercise Implement the function my_strcat – Input – two strings, s1 and s2 Output – a pointer to a dynamically allocated concatenation (‘shirshur’) For example: The concatenation of “hello_” and “world!” is the string “hello_world!” Write a program that accepts two strings from the user and prints their concatenation Assume input strings are no longer than a 100 chars

Solution my_strcat.c (my_strcat2.c)

What’s wrong with this? char *my_strcat(char *str1, char *str2) { int len; char result[500]; /* Let’s assume this is large enough */ len = strlen(str1); strcpy(result, str1); strcpy(result+len, str2); return result; }