0% found this document useful (0 votes)
6 views35 pages

String - 13 05 2024

A pointer is a variable that stores the address of another variable, rather than its value, and must be declared with a specific data type. Strings in C are represented as null-terminated character arrays, and various library functions such as strlen, strcat, and strcpy are available for string manipulation. Understanding the differences between pointers and arrays is crucial for effective memory management in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views35 pages

String - 13 05 2024

A pointer is a variable that stores the address of another variable, rather than its value, and must be declared with a specific data type. Strings in C are represented as null-terminated character arrays, and various library functions such as strlen, strcat, and strcpy are available for string manipulation. Understanding the differences between pointers and arrays is crucial for effective memory management in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

What is a pointer?

 it is a variable, just like other variables


 Difference: it can only store the address
(rather than the value) of a data item
 Type of a pointer variable – pointer to the type
of the data whose address it will store
 Example: int pointer, float pointer,…
 Can be pointer to any user-defined types also like
structure types

1
Values vs Locations

 Variables name memory locations, which hold


values

1024: 32 value
x
address
name

2
Contd.
 Consider the statement
int xyz = 50;
 This statement instructs the compiler to
allocate a location for the integer variable xyz,
and put the value 50 in that location
 Suppose that the address location chosen is
1380 xyz  variable
50  value
1380  address
3
Contd.
 During execution of the program, the system always
associates the name xyz with the address 1380
 The value 50 can be accessed by using either the
name xyz or the address 1380
 Since memory addresses are simply numbers, they
can be assigned to some variables which can be
stored in memory
 Such variables that hold memory addresses are
called pointers
 Since a pointer is a variable, its value is also stored
in some memory location

4
Contd.
 Suppose we assign the address of xyz to a
variable p
 p is said to point to the variable xyz

Variable Value Address p = &xyz;


xyz 50 1380
*p=xyz (50)
p 1380 2545

5
Pointers
 A pointeris just a C variable whose value can contain
the address of another variable
 Needs to be declared before use just like any other
variable
 General form:

data_type *pointer_name;

 Three things are specified in the above declaration:


 The asterisk (*) tells that the variable

pointer_name is a pointer variable


 pointer_name needs a memory location
 pointer_name points to a variable of type

data_type
6
Example
int *count;
float *speed;
char *c;

 Once a pointer variable has been declared, it can be made


to point to a variable using an assignment statement like
int *p, xyz;
:
p = &xyz;
 This is called pointer initialization

7
Strings

8
Strings
• 1-d arrays of type char
• By convention, a string in C is terminated by the
end-of-string sentinel ‘\0’ (null character)
• char s[21] - can have variable length string
delimited with \0
• Max length of the string that can be stored is 20 as the
size must include storage needed for the ‘\0’
• String constants : “hello”, “abc”
• “abc” is a character array of size 4

9
Character Arrays and Strings
char C[8] = { 'a', 'b', 'h', 'i', 'j', 'i', 't', '\0' };
 C[0] gets the value 'a', C[1] the value 'b', and so on.
The last (7th) location receives the null character ‘\0’
 Null-terminated (last character is ‘\0’) character arrays
are also called strings
 Strings can be initialized in an alternative way. The
last declaration is equivalent to:
char C[8] = "abhijit";
 The trailing null character is missing here. C
automatically puts it at the end if you define it like this
 Note also that for individual characters, C uses single
quotes, whereas for strings, it uses double quotes
10
Reading strings: %s format
void main()
{
char name[25];
scanf("%s", name);
printf("Name = %s \n", name);
}

%s reads a string into a character array


given the array name or start address.
It ends the string with ‘\0’

11
An example
void main()
{ Seen on screen
#define SIZE 25
int i, count=0; Typed as input
char name[SIZE]; Satyanarayana
scanf("%s", name); Name = Satyanarayana
printf("Name = %s \n", name); Total a's = 6
for (i=0; name[i]!='\0'; i++)
if (name[i] == 'a') count++;
printf("Total a's = %d\n", Printed by program
count);
}
12
Differences : array & pointers
char *p = “abcde”; char s[ ] = “abcde”;
The compiler  char s[ ] =
allocates space {‘a’,’b’,’c’,’d’,’e’.’\0’};
for p, puts the The compiler allocates 6
string constant
“abcde” in bytes of memory for
memory the array s which are
somewhere
p else, initialized with the 6
initializes p with characters
S a b c d e \0
the base
a b c daddress
e \0
of the string 13
String Constant
• A string constant is treated as a pointer
• Its value is the base address of the string
char *p = “abc”;

p a b c \0

printf (“%s %s\n”,p,p+1);


/* abc bc is printed */

14
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

15
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); //Passing string to a Function
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
} 16
Strings and Pointers
#include <stdio.h>
int main(void)
{
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
} 17
Library Functions for String
Handling
 You can write your own C code to do different
operations on strings like finding the length of a
string, copying one string to another, appending
one string to the end of another etc.
 C library provides standard functions for these
that you can call, so no need to write your own
code
 To use them, you must do
#include <string.h>
At the beginning of your program (after #include
<stdio.h>)
18
String functions we will see
 strlen : finds the length of a string
 strcat : concatenates one string at the end
of another
 strcmp : compares two strings
lexicographically
 strcpy : copies one string to another

19
C strlen() function
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
printf("Length of string a = %zu \n",strlen(a));
printf("Length of string b = %zu \n",strlen(b));
return 0;
}
20
strcpy():
This function is used to copy one string to
another.
Syntax of srtcpy():
char *strcpy(char *dest, const char *src);
Example of srtcpy():

21
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello World";
char dest[20];
strcpy(dest, src);
printf("The copied string is: %s\n", dest);
return 0;
}

22
strcat(): This function is used to concatenate
two strings.
Syntax of strcat():
char *strcat(char *dest, const char *src);

23
int main() {
char str1[] = "Hello";
char str2[] = "World";
strcat(str1, str2);
printf("The concatenated string is: %s\n", str1);
return 0;
}

24
strupr(): It takes a string as input and
converts all the letters in the string to
uppercase.
Syntax of strupr():
char *strupr(char *str);

25
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
// Convert string to uppercase
strupr(str);
printf("Uppercase string: %s\n", str);
return 0;
}
26
strlwr(): It takes a string as input and
converts all the letters in the string to
lowercase.
Syntax of strlwr():
char *strlwr(char *str);

27
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
// Convert string to lowercase
strlwr(str);
printf("Lowercase string: %s\n", str);
return 0;
}
28
strlen() You cannot change contents
of s in the function

int strlen(const char *s)


 Takes a null-terminated
strings (we routinely refer int strlen (const char *s) {
to the char pointer that int n;
points to a null-terminated for (n=0; *s!=‘\0’; ++s)
char array as a string) ++n;
 return n;
Returns the length of
}
the string, not counting
the null (\0) character

29
strcat() You cannot change contents
of s2 in the function
 char *strcat (char *s1,
const char *s2); char *strcat(char *s1, const char
 Takes 2 strings as *s2)
arguments, {
concatenates them, char *p = s1;
while (*p != ‘\0’) /* go to end */
and puts the result in ++p;
s1. Returns s1. while(*s2 != ‘\0’)
Programmer must *p++ = *s2++; /* copy */
ensure that s1 points *p = ‘\0’;
to enough space to return s1;
}
hold the result.
30
strcmp()
int strcmp (const char
*s1, const char *s2);
Two strings are passed
as arguments. An
integer is returned
that is less than,
equal to, or greater
than 0, depending
on whether s1 is
lexicographically
less than, equal to,
or greater than s2. 31
strcmp()
int strcmp (const char
*s1, const char *s2); int strcmp(char *s1, const char *s2)
{
Two strings are passed for (;*s1!=‘\0’&&*s2!=‘\0’; s1++,s2++)
as arguments. An {
integer is returned if (*s1>*s2) return 1;
that is less than, if (*s2>*s1) return -1;
}
equal to, or greater if (*s1 != ‘\0’) return 1;
than 0, depending if (*s2 != ‘\0’) return -1;
on whether s1 is return 0;
lexicographically }
less than, equal to,
or greater than s2. 32
strcpy()
char *strcpy (char *s1, char *s2);
The characters is the string s2 are copied into s1
until \0 is moved. Whatever exists in s1 is
overwritten. It is assumed that s1 has enough space
to hold the result. The pointer s1 is returned.

33
strcpy()
char *strcpy (char *s1, const char *s2);
The characters is the string s2 are copied into s1 until
‘\0’ is moved. Whatever exists in s1 is overwritten. It
is assumed that s1 has enough space to hold the
result. The pointer s1 is returned.

char * strcpy (char *s1, const char *s2)


{
char *p = s1;
while (*p++ = *s2++) ;
return s1;
}
34
Example: Using string functions
int main()
{
char s1[ ] = "beautiful big sky country", Output
s2[ ] = "how now brown cow";
25
printf("%d\n",strlen (s1));
printf("%d\n",strlen (s2+8)); 9
printf("%d\n", strcmp(s1,s2)); -1
printf("%s\n",s1+10); big sky country
strcpy(s1+10,s2+8); beautiful brown cows!
strcat(s1,"s!");
printf("%s\n", s1);
return 0;
}
35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy