SlideShare a Scribd company logo
1 of 23
Review of C
Strings, Arrays and Pointers
C Orientation
• Created in 1972 to write operating systems (Unix
in particular)
– By Dennis Ritchie
– Bell Labs
• Evolved from B
• Can be portable to other hardware
• Built for performance and memory management
– operating systems, embedded systems, real-
time systems, communication systems
What are the advantages of C?
• Portable: allows code to run on different computers and operating
systems without making any change.
• Efficient: It is a general-purpose programming language.
Therefore it works efficiently.
• Case-sensitive: You need to be very careful while writing the code
as it treats lowercase and uppercase letter differently.
• Memory Manipulation and allocation: allows allocating the
memory dynamically.
• Middle-level language: It merges the features of both low level
and high-level languages in itself.
What are the disadvantages of C?
• C language is devoid with the terminology and the concept of
OOPS which is a very popular and an important concept these
days among all high-level programming language.
• No Strict type checking possible.
• No checks for runtime
• It doesn’t give us the provision of having a namespace.
• It also doesn’t have the concept of the constructor as well as a
destructor.
A First Program
#include <stdio.h>
int main(void)
{
printf("This is my first C program.n");
return(0);
}
statements
header
open and close braces mark
the beginning and end
makes input
and output available
to us
A First Program – What Does It Do?
printf("This is my first C program.n");
return(0);
Prints the message
This is my first C program.
Ends the program Ends the line
C Program Phases
• Editor - code by programmer
• Compiling using gcc:
– Preprocess – expand the programmer’s code
– Compiler – create machine code for each file
– Linker – links with libraries and all compiled
objects to make executable
• Running the executable:
– Loader – puts the program in memory to run it
– CPU – runs the program instructions
Copyright © Pearson, Inc. 2013. All
Rights Reserved.
Copyright © Pearson, Inc. 2013. All
Rights Reserved.
Using variables
#include <stdio.h>
int main(void)
{
int sum, value1, value2, value3;
float average;
value1 = 2;
value2 = 4;
value3 = 6;
sum = 2 + 4 + 6;
average = sum / 3;
printf("The average of %d , %d, %d is %fn",
value1, value2, value3, average);
return(0);
}
Print a float value from the
rest of the parameter list
A program that uses a character variable
#include <stdio.h>
/* A very polite program that greets you by name */
int main(void)
{
char name[25];
/* Ask the user his/her name */
printf("What is your name ? ");
scanf("%s", name);
/* Greet the user */
printf("Glad to meet you, %sn.", name);
return(0);
}
Features so far
• Include
• Variable types: int, float, char
• Read using scanf
– requires & for address of variable being read
• Print using printf
• Format strings: %f (float), %d (int), %u
(unsigned int), %c (char), %s (character array)
• Comments /*.. */ or //
Array - Review
• Array – a set of elements all of the same type
stored contiguously in memory – e.g.,
– int A[25]; // 25 integers
– struct Str B[15]; /* 15 objects of
type struct Str */
– double C[]; /* indeterminate #
of doubles */
• Pointer – a variable whose value is the
location of some other object
– float *p; // pointer to a float
Array - Review
int A[25]; // 25 integers
• Type of A[i] is int (for all i).
• Type of A is int *
• I.e., pointer to int
15
Strings in C
• Definition:– A string is a character array ending in
'0' — i.e.,
– char s[256];
– char t[] = "This is an initialized string!";
– char *u = "This is another string!";
• String constants are in double quotes
• May contain any characters
• Including " and '
• String constants may not span lines
• However, they may be concatenated — e.g.,
"Hello, " "World!n" is the same as "Hello, World!n"
16
Strings in C (continued)
• Let
– char *u = "This is another string!";
• Then
– u[0] == 'T'
u[1] == 'h'
u[2] == 'i'
…
u[21] == 'g'
u[22] == '!'
u[23] == '0'
Strings, Arrays, and Pointers CS-2303, C-Term 2010 17
Support for Strings in C
• Most string manipulation is done through functions
in <string.h>
• String functions depend upon final '0'
• So you don’t have to count the characters!
• Examples:–
– int strlen(char *s) – returns length of string
• Excluding final '0'
– char* strcpy(char *s, char *ct) – Copies string ct to
string s, return s
• s must be big enough to hold contents of ct
• ct may be smaller than s
18
Support for Strings in C (continued)
• Examples (continued):–
– int strcmp(char *s, char *t)
• lexically compares s and t, returns <0 if s < t, >0 if
s > t, zero if s and t are identical
– D&D §8.6, K&R p. 106
– char* strcat(char *s, char *ct)
• Concatenates string ct to onto end of string s, returns s
• s must be big enough to hold contents of both strings!
• Other string functions
– strchr(), strrchr(), strspn(), strcspn()
strpbrk(), strstr(), strtok(), …
String - Review
• string.h functions for string manipulation
– String in C – null terminated array of characters
char *s1 = “String1”;
char buff[10];
strcpy(buff, s1);
printf(“%s %dn”, s1, strlen(s1)); // String1 7
buff[3] = ‘0’;
printf(“%s %dn”, s1, strlen(s1)); // Str 3
strcat(buff, “ange”); // buff is Strange
strcmp(s1, “String2”) <= 0 // true (s1 <= “String2”)
Pointers - Review
A pointer is a reference to another variable (memory
location) in a program
– Used to change variables inside a function (reference
parameters)
– Used to remember a particular member of a group (such
as an array)
– Used in dynamic (on-the-fly) memory allocation (especially
of arrays)
– Used in building complex data structures (linked lists,
stacks, queues, trees, etc.)
Pointer - Review
Variables are allocated at addresses in computer memory
(address depends on computer/operating system)
Name of the variable is a reference to that memory address
A pointer variable contains a representation of an address of
another variable (P is a pointer variable in the following):
101
V P
Name
Abstract
Representation
Concrete
Representation
Address
4 bytes for
int value 101
4 bytes for
mem address v
v (some value) p (some value)
int V = 101;
int *P = &V;
Pointer Variable Definition
Basic syntax: Type *Name
Examples:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */
Complex example:
int *AP[5]; /* AP is an array of 5 pointers to ints */
– more on how to read complex declarations later
Sample Program
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and yn");
scanf("%d%d", &x, &y);
printf("Before Swappingnx = %dny = %dn", x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swappingnx = %dny = %dn", x, y);
return 0;
}

More Related Content

Similar to Review of C Strings, Arrays and Pointers

C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with Cgpsoft_sk
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011Patrick Walton
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxSreeLaya9
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).pptadvRajatSharma
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
Script of Scripts Polyglot Notebook and Workflow System
Script of ScriptsPolyglot Notebook and Workflow SystemScript of ScriptsPolyglot Notebook and Workflow System
Script of Scripts Polyglot Notebook and Workflow SystemBo Peng
 

Similar to Review of C Strings, Arrays and Pointers (20)

C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
 
Cpu
CpuCpu
Cpu
 
C programming language
C programming languageC programming language
C programming language
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Script of Scripts Polyglot Notebook and Workflow System
Script of ScriptsPolyglot Notebook and Workflow SystemScript of ScriptsPolyglot Notebook and Workflow System
Script of Scripts Polyglot Notebook and Workflow System
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 

Review of C Strings, Arrays and Pointers

  • 1. Review of C Strings, Arrays and Pointers
  • 2. C Orientation • Created in 1972 to write operating systems (Unix in particular) – By Dennis Ritchie – Bell Labs • Evolved from B • Can be portable to other hardware • Built for performance and memory management – operating systems, embedded systems, real- time systems, communication systems
  • 3. What are the advantages of C? • Portable: allows code to run on different computers and operating systems without making any change. • Efficient: It is a general-purpose programming language. Therefore it works efficiently. • Case-sensitive: You need to be very careful while writing the code as it treats lowercase and uppercase letter differently. • Memory Manipulation and allocation: allows allocating the memory dynamically. • Middle-level language: It merges the features of both low level and high-level languages in itself.
  • 4. What are the disadvantages of C? • C language is devoid with the terminology and the concept of OOPS which is a very popular and an important concept these days among all high-level programming language. • No Strict type checking possible. • No checks for runtime • It doesn’t give us the provision of having a namespace. • It also doesn’t have the concept of the constructor as well as a destructor.
  • 5. A First Program #include <stdio.h> int main(void) { printf("This is my first C program.n"); return(0); } statements header open and close braces mark the beginning and end makes input and output available to us
  • 6. A First Program – What Does It Do? printf("This is my first C program.n"); return(0); Prints the message This is my first C program. Ends the program Ends the line
  • 7. C Program Phases • Editor - code by programmer • Compiling using gcc: – Preprocess – expand the programmer’s code – Compiler – create machine code for each file – Linker – links with libraries and all compiled objects to make executable • Running the executable: – Loader – puts the program in memory to run it – CPU – runs the program instructions
  • 8. Copyright © Pearson, Inc. 2013. All Rights Reserved.
  • 9. Copyright © Pearson, Inc. 2013. All Rights Reserved.
  • 10. Using variables #include <stdio.h> int main(void) { int sum, value1, value2, value3; float average; value1 = 2; value2 = 4; value3 = 6; sum = 2 + 4 + 6; average = sum / 3; printf("The average of %d , %d, %d is %fn", value1, value2, value3, average); return(0); } Print a float value from the rest of the parameter list
  • 11. A program that uses a character variable #include <stdio.h> /* A very polite program that greets you by name */ int main(void) { char name[25]; /* Ask the user his/her name */ printf("What is your name ? "); scanf("%s", name); /* Greet the user */ printf("Glad to meet you, %sn.", name); return(0); }
  • 12. Features so far • Include • Variable types: int, float, char • Read using scanf – requires & for address of variable being read • Print using printf • Format strings: %f (float), %d (int), %u (unsigned int), %c (char), %s (character array) • Comments /*.. */ or //
  • 13. Array - Review • Array – a set of elements all of the same type stored contiguously in memory – e.g., – int A[25]; // 25 integers – struct Str B[15]; /* 15 objects of type struct Str */ – double C[]; /* indeterminate # of doubles */ • Pointer – a variable whose value is the location of some other object – float *p; // pointer to a float
  • 14. Array - Review int A[25]; // 25 integers • Type of A[i] is int (for all i). • Type of A is int * • I.e., pointer to int
  • 15. 15 Strings in C • Definition:– A string is a character array ending in '0' — i.e., – char s[256]; – char t[] = "This is an initialized string!"; – char *u = "This is another string!"; • String constants are in double quotes • May contain any characters • Including " and ' • String constants may not span lines • However, they may be concatenated — e.g., "Hello, " "World!n" is the same as "Hello, World!n"
  • 16. 16 Strings in C (continued) • Let – char *u = "This is another string!"; • Then – u[0] == 'T' u[1] == 'h' u[2] == 'i' … u[21] == 'g' u[22] == '!' u[23] == '0'
  • 17. Strings, Arrays, and Pointers CS-2303, C-Term 2010 17 Support for Strings in C • Most string manipulation is done through functions in <string.h> • String functions depend upon final '0' • So you don’t have to count the characters! • Examples:– – int strlen(char *s) – returns length of string • Excluding final '0' – char* strcpy(char *s, char *ct) – Copies string ct to string s, return s • s must be big enough to hold contents of ct • ct may be smaller than s
  • 18. 18 Support for Strings in C (continued) • Examples (continued):– – int strcmp(char *s, char *t) • lexically compares s and t, returns <0 if s < t, >0 if s > t, zero if s and t are identical – D&D §8.6, K&R p. 106 – char* strcat(char *s, char *ct) • Concatenates string ct to onto end of string s, returns s • s must be big enough to hold contents of both strings! • Other string functions – strchr(), strrchr(), strspn(), strcspn() strpbrk(), strstr(), strtok(), …
  • 19. String - Review • string.h functions for string manipulation – String in C – null terminated array of characters char *s1 = “String1”; char buff[10]; strcpy(buff, s1); printf(“%s %dn”, s1, strlen(s1)); // String1 7 buff[3] = ‘0’; printf(“%s %dn”, s1, strlen(s1)); // Str 3 strcat(buff, “ange”); // buff is Strange strcmp(s1, “String2”) <= 0 // true (s1 <= “String2”)
  • 20. Pointers - Review A pointer is a reference to another variable (memory location) in a program – Used to change variables inside a function (reference parameters) – Used to remember a particular member of a group (such as an array) – Used in dynamic (on-the-fly) memory allocation (especially of arrays) – Used in building complex data structures (linked lists, stacks, queues, trees, etc.)
  • 21. Pointer - Review Variables are allocated at addresses in computer memory (address depends on computer/operating system) Name of the variable is a reference to that memory address A pointer variable contains a representation of an address of another variable (P is a pointer variable in the following): 101 V P Name Abstract Representation Concrete Representation Address 4 bytes for int value 101 4 bytes for mem address v v (some value) p (some value) int V = 101; int *P = &V;
  • 22. Pointer Variable Definition Basic syntax: Type *Name Examples: int *P; /* P is var that can point to an int var */ float *Q; /* Q is a float pointer */ char *R; /* R is a char pointer */ Complex example: int *AP[5]; /* AP is an array of 5 pointers to ints */ – more on how to read complex declarations later
  • 23. Sample Program #include <stdio.h> int main() { int x, y, *a, *b, temp; printf("Enter the value of x and yn"); scanf("%d%d", &x, &y); printf("Before Swappingnx = %dny = %dn", x, y); a = &x; b = &y; temp = *b; *b = *a; *a = temp; printf("After Swappingnx = %dny = %dn", x, y); return 0; }