Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

C Programming : Pointers and Strings

Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio

Eche un vistazo a continuación

1 de 93 Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a C Programming : Pointers and Strings (20)

Anuncio

Más de Selvaraj Seerangan (20)

Más reciente (20)

Anuncio

C Programming : Pointers and Strings

  1. 1. C Programming : Pointer and Strings By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  2. 2. 20CST11 – Problem Solving and Programming 3/2/2021 4.1 Pointers 2 Syllabus
  3. 3. Contents 1. Pointers – Memory Access and Pointers – Pointer basics – Declaring, Initializing and Dereferencing a pointer – Parameter Passing Mechanisms – Operations on Pointers 2. Strings – String Basics – Declaring and Initializing a String – Pointers for String Manipulation – String handling functions – Standard and user defined functions – character oriented functions – Two dimensional array of strings 3/2/2021 3 4.1 Pointers
  4. 4. Memory Access and Pointers • A program evaluates a variable by accessing its memory location and retrieving the value stored there. • C permits every legal area of memory to be directly accessed. • “legal” because not every memory location is accessible by our programs. • The language allows us to obtain the memory location of every variable, array or structure used in a program. • We can then use the address of this location to access—and even change—the value stored there. • Two values are associated with any variable: – the address of its memory location and – the value stored at the location 3/2/2021 4.1 Pointers 4
  5. 5. Pointer Basics • A pointer is a variable with a difference. • It contains, not a simple value, but the address of another variable or object. • For example, • if a pointer p is assigned the address of an int variable x which is set to 5, then • where – &x evaluates to the memory address of x. 3/2/2021 4.1 Pointers 5
  6. 6. Pointer Basics • The pointer p must have been declared previously as • C offers two unary operators, the & and *, for handling pointers. 3/2/2021 4.1 Pointers 6
  7. 7. Pointer Basics • The & is used to obtain the address of a variable. • The * is used for two purposes. • One, to declare the pointer. – When p is assigned the address of x, p is said to point to x, which means you can use p to access and change x. • Second, to obtain the value at the address pointed. – If p is visible at some location of a program but x is not, you can still access x at that location by dereferencing p to obtain the value at the address pointed to, i.e. x. – The expression *p (second use of *) evaluates to x: 3/2/2021 4.1 Pointers 7
  8. 8. Pointer Basics • While *p represents the value of x, it can also be used on the left-hand side of an assignment to change the value of x: • The power of a pointer lies in the preceding statement. The assignment *p = 10 is the same as x = 10. • A pointer thus provides access to two values— – the address it stores and – the value stored at the address 3/2/2021 4.1 Pointers 8
  9. 9. Pointer Basics • The type of this pointer is not int, but pointer to int, which we also refer to as int *. • Even though a pointer has an integer value, it supports a limited form of arithmetic. – Adding 1 to a pointer value of 100 yields 101 when the pointed-to variable is of type char, – and 104 when the pointed-to variable is of type int. • Using pointer arithmetic, we can navigate memory and update the contents at any legal memory location. • You can change the value stored in the pointer or the value pointed to: 3/2/2021 4.1 Pointers 9
  10. 10. Pointer Basics • Like arrays, pointers belong to the category of derived data types. • Since every variable has an address, – we can define pointers for every data type, including arrays and structures. – We can also create a pointer to another pointer. • Arrays and strings can also be treated as pointers for most purposes. – The name of an array evaluates to the address of the first element. – Double-quoted string evaluates to the address of the first character of the string. 3/2/2021 4.1 Pointers 10
  11. 11. Pointer Basics 3/2/2021 4.1 Pointers 11
  12. 12. 3/2/2021 4.1 Pointers 12
  13. 13. Declaring, Initializing and Dereferencing a pointer • A pointer variable is declared (and automatically defined) before use. • Declaration specifies the type and allocates the necessary memory for the pointer. • The following statement declares a pointer variable named p that can store the address of an int variable. • By convention, the * is prefixed to the variable, but you can place it anywhere between int and p – Int *p – int * p – int* p 3/2/2021 4.1 Pointers 13
  14. 14. Declaring, Initializing and Dereferencing a pointer • The pointer p, which now contains an unpredictable value, can be used only after it is made to point to a legal memory location. • This can be the address of an int variable (say, x), which is obtained by using the & operator: • The & operator evaluates its operand (x) as an address. • We can combine the declaration and assignment in this manner: 3/2/2021 4.1 Pointers 14
  15. 15. Declaring, Initializing and Dereferencing a pointer • p has the data type int *, or pointer to int, which simply means that the value pointed to has the type int. • Similarly, a float variable is pointed to by a pointer of type float * or pointer to float. • However, the size of the pointer itself has no relation to the size of the variable pointed to. • A pointer has a fixed size and its value is printed with the %p format specifier of printf. • After a pointer has been assigned a valid address with p = &x; • Use the concept of indirection to obtain the value of x from p. • The expression *p evaluates to x. 3/2/2021 4.1 Pointers 15
  16. 16. Declaring, Initializing and Dereferencing a pointer • The *, used as a unary operator in dereferencing or indirection, operates in the following sequence: – It evaluates its operand (p) to obtain the stored address (&x) – It then fetches the value (x) stored at that address • Hence, *p is synonymous with x and can be used wherever x is used. • Thus, *p changes x when used in the following way: 3/2/2021 4.1 Pointers 16
  17. 17. Declaring, Initializing and Dereferencing a pointer • As long as p points to x, any change made to x can be seen by p, and vice versa. • This is the most important feature of a pointer. • p thus has two values— – a direct (&x) and – an indirect one (*p). • The dereferenced value of p can also be assigned to another variable or used in an arithmetic expression: 3/2/2021 4.1 Pointers 17
  18. 18. Declaring, Initializing and Dereferencing a pointer • The relationship between a pointer and the variable it points to is depicted in Figure. 3/2/2021 4.1 Pointers 18
  19. 19. 3/2/2021 4.1 Pointers 19
  20. 20. Parameter Passing Mechanism • There are different ways in which parameter data can be passed into and out of methods and functions. • Let us assume that a function B() is called from another function A(). • In this case A is called the “caller function” and B is called the “called function or callee function”. • Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments. 3/2/2021 4.1 Pointers 20
  21. 21. Parameter Passing Mechanism • Formal Parameter : A variable and its type as they appear in the prototype of the function or method. • Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment. • Modes: – IN: Passes info from caller to calle. – OUT: Callee writes values in caller. – IN/OUT: Caller tells callee value of variable, which may be updated by callee. 3/2/2021 4.1 Pointers 21
  22. 22. Pass By Value / Call By Value • This method uses in-mode semantics. • Changes made to formal parameter do not get transmitted back to the caller. • Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. • This method is also called as call by value. 3/2/2021 4.1 Pointers 22
  23. 23. Call By Value 3/2/2021 4.1 Pointers 23
  24. 24. Example 3/2/2021 4.1 Pointers 24
  25. 25. • Shortcomings: – Inefficiency in storage allocation – For objects and arrays, the copy semantics are costly 3/2/2021 4.1 Pointers 25
  26. 26. Pass by reference / Call by reference • This technique uses in/out-mode semantics. • Changes made to formal parameter do get transmitted back to the caller through parameter passing. • Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. • This method is also called as call by reference. • This method is efficient in both time and space. 3/2/2021 4.1 Pointers 26
  27. 27. Call by reference 3/2/2021 4.1 Pointers 27
  28. 28. Example 1 3/2/2021 4.1 Pointers 28
  29. 29. Example 2 3/2/2021 4.1 Pointers 29
  30. 30. 3/2/2021 4.1 Pointers 30
  31. 31. • Shortcomings: – Many potential scenarios can occur – Programs are difficult to understand sometimes 3/2/2021 4.1 Pointers 31
  32. 32. Other methods of Parameter Passing • These techniques are older and were used in earlier programming languages like Pascal, Algol and Fortran. • These techniques are not applicable in high level languages. – Pass by Result : This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called call by result. In general, pass by result technique is implemented by copy. – Pass by Value-Result : This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-result. – Pass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update. 3/2/2021 4.1 Pointers 32
  33. 33. Operations on Pointers • Apart from dereferencing with the *, there are a number of operations that can be performed on pointers. • We consider here three types of operations: – Assignment – Arithmetic and – Comparison, • using a pointer p that points to int. 3/2/2021 4.1 Pointers 33
  34. 34. Assignment • A pointer can be assigned – the address of a variable (p = &c;) or – the name of an array (p = arr;) • It can also be assigned the value of another pointer variable of the same type. 3/2/2021 4.1 Pointers 34
  35. 35. Assignment • It is possible to assign an integer, suitably cast to the type of the pointer, to a pointer variable using. • However, you can, and often will, assign the value 0 to a pointer. This value has a synonym in the symbolic constant, NULL. • You can assign either 0 or NULL to a pointer of any type without using a cast 3/2/2021 4.1 Pointers 35
  36. 36. Pointer Arithmetic Using + and - • The domain of pointer arithmetic is small and simple. • Among the basic arithmetic operators, only the + and - can be used with pointers. • An integer may be added to or subtracted from a pointer. • The resultant increase or decrease occurs in terms of storage units, so p + 2 advances the pointer by two storage units (12.8.1). • For an array, this means skipping two elements. • The following operations on &x and an array element are also permitted: 3/2/2021 4.1 Pointers 36
  37. 37. Pointer Arithmetic Using + and - 3/2/2021 4.1 Pointers 37
  38. 38. Pointer Arithmetic Using + and - 3/2/2021 4.1 Pointers 38
  39. 39. Pointer Arithmetic Using ++ and -- • A pointer variable can also be used with the increment and decrement operators. • Because ++ and -- have the side effect of changing their operand, they can’t be used with the name of the array which is a constant pointer. • The following expressions are not permitted for the array arr: 3/2/2021 4.1 Pointers 39
  40. 40. Pointer Arithmetic Using ++ and -- • But if p points to arr, the expressions p++ or -- p are legal. • p++ increases the pointer to point to the next array element and p-- decrements it to point to the previous element. • If p points to an int variable, each ++ or -- operation changes the numerical value of the pointer by 4 bytes. 3/2/2021 4.1 Pointers 40
  41. 41. Pointer Arithmetic Using ++ and -- • The expressions p++ and p-- are often combined with the * for dereferencing the pointer. • Expressions like *p++ and ++*p are commonly used in programs to evaluate the value pointed to by p, before or after the incrementing operation. 3/2/2021 4.1 Pointers 41
  42. 42. Example 3/2/2021 4.1 Pointers 42
  43. 43. Comparing Two Pointers • Finally, two pointers can be compared only if they point to members of the same array. • There are two exceptions though. – First, any pointer can be compared to the null pointer (p == NULL) that is often returned by a function when an error condition is encountered. – Also, a pointer of any type can be compared to a generic or void pointer 3/2/2021 4.1 Pointers 43
  44. 44. Thank you 3/2/2021 4.1 Pointers 44
  45. 45. C Programming : Pointer and Strings By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  46. 46. 20CST11 – Problem Solving and Programming 3/2/2021 4.2 Strings 46 Syllabus
  47. 47. Contents 1. Pointers – Memory Access and Pointers – Pointer basics – Declaring, Initializing and Dereferencing a pointer – Parameter Passing Mechanisms – Operations on Pointers 2. Strings – String Basics – Declaring and Initializing a String – Pointers for String Manipulation – String handling functions – Standard and user defined functions – character oriented functions – Two dimensional array of strings 3/2/2021 47 4.2 Strings
  48. 48. Strings Basics • Unlike Java, C doesn’t support a primary data type for a string. • The language approaches strings through the “backdoor”—by tweaking the char data type. • A string belongs to the category of derived data types and is interpreted as an array of type char terminated by the NUL character. • C offers no keywords or operators for manipulating strings but its standard library supports a limited set of string-handling functions. 3/2/2021 4.2 Strings 48
  49. 49. Strings Basics • Even though a string is a collection of characters, they are interpreted differently. • A character constant is a single-byte integer whose equivalent symbol is enclosed in single quotes. – Thus, ‘A’ and its ASCII value, 65, can be used interchangeably in programs. • But a string constant is a set of one or more characters enclosed in double quotes. – Thus, “A” signifies a string. – ‘A’ uses one byte but “A” needs two bytes which include the NUL character. • Functions that operate on characters don’t work with strings and vice versa. 3/2/2021 4.2 Strings 49
  50. 50. Strings Basics • The pointer introduces an additional dimension to a string. • The string constant “Micromax” represents a pointer to the address of its first character. – i.e., 'M'. • This string can thus be assigned to a pointer variable of type char *. • A string can be manipulated with both array and pointer notation even though they are not entirely equivalent. 3/2/2021 4.2 Strings 50
  51. 51. Strings Basics • Because strings don’t have fixed sizes, every string- handling function must know where a string begins and where it ends. – A function knows the beginning of a string from the pointer associated with it. – The end is signified by the NUL character. • Functions of the standard library that create or modify strings make sure that the NUL is always in place. • However, when you create a string-handling function, it’s your job to append the NUL at the end of the string. • NUL has the decimal value 0 and is represented by the escape sequence ‘0’. 3/2/2021 4.2 Strings 51
  52. 52. Declaring and Initializing a String • A string can be declared either as – an array of type char or – as a pointer of type char *. • The two techniques of declaration are not fully equivalent. • You must understand how they differ and when to use one technique in preference to the other. 3/2/2021 4.2 Strings 52
  53. 53. Using an Array to Declare a String • We have previously declared and initialized an array with a set of values enclosed in curly braces. • The same technique applies to strings as well. • The following declaration (and definition) statements also include initialization with a set of single-quoted characters: 3/2/2021 4.2 Strings 53
  54. 54. Using an Array to Declare a String • The last element in each case is NUL. • It has to be explicitly inserted when you initialize a string like this. • The first declaration wastes space because the string uses only nine elements. • But the compiler automatically sets the size of stg2 by counting eight items in the list. 3/2/2021 4.2 Strings 54
  55. 55. Using an Array to Declare a String • Keying in single-quoted characters for initialization is a tedious job, so C also offers a convenient alternative. • You can use a double-quoted string to assign an array at the time of declaration. • The NUL is automatically inserted when an array is assigned in this way. • So, even though sizeof stg1 evaluates to 20 (the declared size), sizeof stg2 and sizeof stg3 evaluate to 8 and 9 respectively. 3/2/2021 4.2 Strings 55
  56. 56. When an Array is Declared But Not Initialized 3/2/2021 4.2 Strings 56
  57. 57. Using a Pointer to Declare a String • C supports another way of creating a string. • Declare a pointer to char. • Assign a double-quoted string to the pointer variable. 3/2/2021 4.2 Strings 57
  58. 58. Using a Pointer to Declare a String • This string comprises multiple words which – scanf reads with two %s specifiers, but – printf needs a single %s to print. • Like with a regular variable, you can combine declaration and initialization in one statement. 3/2/2021 4.2 Strings 58
  59. 59. Using a Pointer to Declare a String • The previous declarations that used an array allocated memory only for the array. • But the preceding one creates space in memory for two objects. – for the pointer p and – for the string constant, “Redmi Note” • It then makes p point to the first character of the string. 3/2/2021 4.2 Strings 59
  60. 60. 3/2/2021 4.2 Strings 60
  61. 61. When an Array of Characters Is Not a String • An array of characters is not a string when it doesn’t include the ‘0’ character as the terminator. • Usually, we don’t bother to include the NUL because the compiler does this job for us, • but negligence on our part can prevent the compiler from doing so. 3/2/2021 4.2 Strings 61
  62. 62. When an Array of Characters Is Not a String • Consider the following declarations • In this scenario, stg5 has no space left to store the NUL character. • When printf encounters this string, it continues printing beyond the ‘t’ until it encounters a NUL somewhere on the way. • This means looking at a region of memory not reserved for it. • You may see extra characters printed at the end of the word float or the program could even crash. • The NUL character has not been explicitly inserted in stg6, so one would be tempted to conclude that stg6 is not a string. • However, stg6 is a partially initialized array, which by definition, has the uninitialized elements set to NUL. Hence, stg6 is a string. 3/2/2021 4.2 Strings 62
  63. 63. 3/2/2021 4.2 Strings 63
  64. 64. 3/2/2021 4.2 Strings 64
  65. 65. 3/2/2021 4.2 Strings 65
  66. 66. Pointers for String Manipulation • String manipulation is an important programming activity. – Navigating a string and – Accessing each character • a string can be treated as an array and a pointer. • By using pointer and array notation in pointer arithmetic we can manipulate strings. 3/2/2021 4.2 Strings 66
  67. 67. Pointers for String Manipulation • Consider the following strings defined in two different ways: • Because stg is a constant, we can use limited pointer arithmetic (like stg + 1) to access and update each element, but we cannot use stg++ and stg--. • The pointer p, being a variable, knows no such restrictions. In addition to using expressions like p + 1, we can also use p++ and p-- to change the current pointer position in the string. 3/2/2021 4.2 Strings 67
  68. 68. Pointers for String Manipulation • There is one more difference between stg and p. • you can change the contents of stg (“Nyasaland”). • you can’t change the dereferenced value of p (“Malawi”) because p is a pointer constant. • p points to a region of memory that is marked read-only. • However, if p is made to point to stg, then you can change any character in stg using p. 3/2/2021 4.2 Strings 68
  69. 69. Pointers for String Manipulation 3/2/2021 4.2 Strings 69
  70. 70. 3/2/2021 4.2 Strings 70
  71. 71. 3/2/2021 4.2 Strings 71
  72. 72. String Handling Functions • There are five string-handling functions can be perform basically. – Function to Evaluate Length of a String – Function to Reverse a String – Function to Copy a String – Function to Concatenate Two Strings – Function to Extract a Substring 3/2/2021 4.2 Strings 72
  73. 73. Function to Evaluate Length of a String 3/2/2021 4.2 Strings 73
  74. 74. Function to Reverse a String 3/2/2021 4.2 Strings 74
  75. 75. Function to Copy a String 3/2/2021 4.2 Strings 75
  76. 76. Function to Concatenate Two Strings 3/2/2021 4.2 Strings 76
  77. 77. 3/2/2021 4.2 Strings 77
  78. 78. 3/2/2021 4.2 Strings 78
  79. 79. Standard String Handling Functions 3/2/2021 4.2 Strings 79
  80. 80. Scan Set %[...] / %[^...] • A format specifier of the scanf function that uses a set of characters enclosed by [ and ] • Used for matching characters that either belong or don’t belong to the set. • The format specifier %[^n] represents a scan set that matches an entire line not containing the newline character. 3/2/2021 4.2 Strings 80
  81. 81. Strlen () 3/2/2021 4.2 Strings 81
  82. 82. Strcpy() 3/2/2021 4.2 Strings 82
  83. 83. Strcat() 3/2/2021 4.2 Strings 83
  84. 84. strcmp() 3/2/2021 4.2 Strings 84
  85. 85. Strchr() 3/2/2021 4.2 Strings 85
  86. 86. Strstr() 3/2/2021 4.2 Strings 86
  87. 87. Character oriented functions • C supports a number of character-handling functions. • All character-oriented functions need the #include <ctype.h> directive. • Most of these functions test a specific attribute and simply return true or false. • For instance, the isdigit function can be used in a loop to validate a string that must not have any digits. 3/2/2021 4.2 Strings 87
  88. 88. 3/2/2021 4.2 Strings 88
  89. 89. 3/2/2021 4.2 Strings 89
  90. 90. Two Dimensional Array of Strings • A string can be stored in an array of type char. • Multiple strings can be stored in a two- dimensional array. • The number of strings that can be stored is determined by the number of rows (first subscript). • the maximum length of each string is set by the number of columns (second subscript). 3/2/2021 4.2 Strings 90
  91. 91. Two Dimensional Array of Strings • Here’s how we assign four strings to a 2D array of type char: • When using this technique, we need the inner braces because all four strings are shorter than the number of columns (12). • This is not a convenient way of populating arrays with strings. 3/2/2021 4.2 Strings 91
  92. 92. Two Dimensional Array of Strings • A simpler method is to use a set of double- quoted strings enclosed in a single set of braces: 3/2/2021 4.2 Strings 92
  93. 93. Thank you 3/2/2021 4.2 Strings 93

×