C Programming
Strings and Arrays
1
Copyright 2006 Wipro Technologies Copyright 2006 Wipro Technologies
Agenda
Arrays Strings
2
Copyright 2006 Wipro Technologies
Agenda Diagram Representation
The following is a diagrammatic model to understand the c program well. It is nothing but Pictorial Representation of variables.
Data Type
Any variable either it is normal or pointer can be represented using this diagram. Lets take one simple example int i = 10; char c = 100;
Starting address
<value>
Variable Name int Ending address
10
Note: 32 bit system Size of character is 1 byte Size of Integer is 4 byte
char
1000
1003
Size of float is 4 byte
Size of double is 8 byte
100
3
Copyright 2006 Wipro Technologies 2000 p 2001
Arrays Basic Concepts
A contiguous group of data items. It has a name which identifies the array Each item / element, in an array is of the same data type An array item is accessed by an index Use the array subscript operator [] Index starts at 0 and ends at n -1 Array can be single or multiple dimensions
4
Copyright 2006 Wipro Technologies
Array Representation
This will create an area in memory for a, which is 6*sizeof (int)
int a[6] = {1,2,3,4,5,6};
What is the value of a? What is the value of a[0]? What is the value of &a[2] ? => What is the value of *(&a[2]) ?
1000
3
a
6
1023
1008 ???
The above expression can be rewritten as a[2] The above expression can be rewritten in pointer notation as *(a+2)
5
Copyright 2006 Wipro Technologies
Arrays - Declaration
The declaration can be single or multiple dimension Array Initialization can be any of the following types
Separate Initialization lists Sized vs unsized
6
Copyright 2006 Wipro Technologies
Arrays Single Dimension Array Declaration & Initialization list
Data type name [size] where size is an integer constant expression
Eg: int intarray [ 15 ] float floatarray [ 20 ] char chararray [ 256 ]
Initialization List
Data type name [ size ] = {initval0, initval1, } where size is an integer constant expression and items in the initialization lists are constant expressions.
Eg: int intarray [ 5 ] = {1, 2, 3, 4, 5}
float floatarray [2] = {1.5f, 2.3f} char chararray [2] = {h, i}
7
Copyright 2006 Wipro Technologies
Data Types Arrays Single Dimension Array Declaration Unsized Initialization list Data type name [] = {initval0,.. Initvaln } where initvals are constant expressions
Eg: int intarray [ ] = {1,2,3,4} (Note: sizeof) float floatarray [ ] = {1.5f, 2.5f} char chararray [ ] = {a, b, c } Size of array indicated by number of initializers (Need to give examples)
8
Copyright 2006 Wipro Technologies
Data Types Arrays Multi Dimension Array Declaration & sized Initialization list
Data type name [size1][size2] where size1 and size2 are integer constant expressions
Eg: int intarray [2][3]
With sized initialization list
Data type name [size1][size2] = {{initval0,.}, {. Initvaln} } where size1 and size2 are integer constant expressions and initvals are constant expressions
Eg: int intarray [2][3] = {{1,2,3},{4,5,6}}
With unsized initialization list
Data type name [ ][size2] = {{initval0,.}, {. Initvaln} } where size2 is integer constant expressions and initvals are constant expressions
Eg: int intarray[ ] [3] = {{1,2,3},{4,5,6}}
Only the first dimension can be unsized
9
Copyright 2006 Wipro Technologies
Data Types Single Dimension Array Sample
// single dimension arrays int main() { int grades[10]; // array declaration int i; // separate initialization for ( i = 0; i < 10; i++ ) { grades [ i ] = 0; } // array usage grades [ 0 ] = 100; grades [ 1 ] = grades [ 0 ] 10; return 0; }
10
Copyright 2006 Wipro Technologies
// as lvalue // lvalue and rvalue
Data Types Single Dimension Array Sample
/* single dimension arrays with initialization list */ int main() { /* array declaration*/ int grades [ 5 ] = { 95, 60, 93, 92, 94 }; int i; /* arrays go well with for loops */ for ( i = 0; i < 5; i++ ) { /* array usage */
printf (Grade %i is %i \n, i, grades [ i ] );
} }
11
Copyright 2006 Wipro Technologies
Data Types Single Dimension Array Sample
// single dimension arrays with initialization list (unsized) int main() { // array declaration int grades [ ] = { 95, 90, 93, 92, 94 }; int i, size; size = sizeof ( grades) / sizeof ( int ); // arrays go well with for loops for ( i = 0; i < size; i++ ) { // array usage
printf (Grade %d is %d \n, i, grades [ i ] );
} return 0; }
12
Copyright 2006 Wipro Technologies
Data Types Multi Dimension Array Sample
// multiple dimension arrays with initialization list main() { // array declaration int ages [ 2 ] [ 3 ] = { { 22, 21, 55 }, { 33, 29, 40 } }; int i, j; // arrays go well with for loops for ( i = 0; i < 2; i++ ) { for ( j = 0; j < 3; j++ ) { // array usage
printf (Age %d,%d is %d\n, i, j, ages [ i ] [ j ] ); }
} }
13
Copyright 2006 Wipro Technologies
Strings
There are no Strings in C.
There is an agreed upon convention to store string like data structures in arrays of characters.
Part of the convention includes terminating strings with a null character. In many cases "string" operations in C look just like those found in other languages. Do not be deceived. This is C...memory must be managed properly (by you)!
14
Copyright 2006 Wipro Technologies
Strings
#include <stdio.h> #include <string.h> int main() { char chararray[] = {'H','e','l','l','o'}; char word[] = {'H','e','l','l','o','\0'}; char string[] = "This is string"; printf("chararray = %s\n", chararray); printf("word = %s\n", word); printf("string = %s\n", string); chararray = Hello word = Hello string = This is string string length of chararray is 5 size of chararray is 5 string length of word size of word is 5 is 6
string length of string is 14 size of string is 15
printf("string length of chararray is %d \n", strlen(chararray)); printf("size of chararray is %d \n\n", sizeof(chararray)); printf("string length of word is %d \n", strlen(word)); printf("size of word is %d \n\n", sizeof(word)); printf("string length of string is %d \n", strlen(string)); printf("size of string is %d \n\n", sizeof(string)); return 0; }
Copyright 2006 Wipro Technologies
Note: Sizeof function returns the memory occupied by the strings including \o character Strlen() function returns the length of the string, which 15 excludes the \o (null) character
Strings
char *a = "Hello "; char *b = "world"; strcat(a, b); printf("%s\n", a); What do you expect in the output?
char a[12] = "Hello "; char *b = "world"; strcat(a, b); printf("%s\n", a);
Here, char *a, and char *b are pointing to literal constant string and it will be stored in constant data area. We can not change the constant data The program will produce segmentation fault.
char *a; char *b = World; a = (char *) malloc (sizeof (char) * 15); strcpy(a, Hello ); strcat(a, b); printf("%s\n", a); 16 free(a);
Copyright 2006 Wipro Technologies
Strings
We can represent the strings in a diagram.
char string[12] = Hello ; char *b = world; H strcat (string, b); printf(%s\n, string); 1000 Output: Hello World
char char
\0
\0 w
\0
1000 char *
string
1011
w 4000 4000
\0
4005
5000 b Copyright 2006 Wipro Technologies
5003
17
Strings
We implement string-like data structures using array of characters
char s1[10]; /* Not a string! ??? */
char *s2; /* Not a string! */ char s3[10] = "foo"; /* Not a string ??? */ char *s4 = "bar";
What acts like a string? A pointer to a character followed by a sequence of characters terminating in a null byte
char s5[10] = "foo";
f o o \0 ?? ?? ?? ?? ?? ??
18
Copyright 2006 Wipro Technologies
Strings String functions
#include <string.h> strcpy(p, s); strcmp(p, s); strcat(p, s); strlen(s); char *strchr(const char *string, int c) char *strstr(const char *S1, const char *S2) char *strtok(char *SOURCE, char *DELIMITERS)
Note: strcpy and strcat dont malloc space p must be allocated to be large enough to hold the results char s1[10] = "foo"; char *s2 = "foobar"; strcpy(s2, s1); /* Okay? */ No! strcpy(s1, s2); /* Okay? */ Yes!
19
Copyright 2006 Wipro Technologies
Strings String functions
strdup It is used to duplicate a string
#include <string.h> char *strdup (const char *s);
What does it do? Different than strcpy? Cautions? It allocates memory using malloc and copies into it the string addressed by s, including null terminated character. It is developers responsibility to free the allocated storage by calling free function
20
Copyright 2006 Wipro Technologies
Strings String functions
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *word = NULL; char *string = Hello World;
word = strdup(string);
printf(%s\n, word); free(word);
return EXIT_SUCCESS;
}
Output:
Hello World
21
Copyright 2006 Wipro Technologies
Strings String functions
gets char *gets(char *s);
gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. No check for buffer overrun is performed! Leads to buffer overflow
Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
22
Copyright 2006 Wipro Technologies
Strings String functions
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char buffer[10]; gets(buffer); printf("buffer = %s\n", buffer); return EXIT_SUCCESS; }
Output: $ outputgets Hello buffer = Hello
$outputgets
Now is the time for all good men to come to the aid of their buffer = Now is the time for all good men to come to the aid of their Segmentation fault
23
Copyright 2006 Wipro Technologies
Strings String functions
strtok - extract token from string
#include <string.h>
char *strtok (char *s, const char *delim);
A `token' is a nonempty string of characters not occurring in the string delim, followed by \0 or by a character occurring in delim. The strtok() function can be used to parse the string s into tokens. The first call to strtok() should have s as its first argument. Subsequent calls should have the first argument set to NULL. Each call returns a pointer to the next token, or NULL when no more tokens are found.
24
Copyright 2006 Wipro Technologies
Strings String functions
If a token ends with a delimiter, this delimiting character is overwritten with a \0 and a pointer to the next character is saved for the next call to strtok. The delimiter string delim may be different for each call. This function modifies its first argument. The identity of the delimiting character is lost. This function cannot be used on constant strings. The strtok() function returns a pointer to the next token, or NULL if there are no more tokens.
25
Copyright 2006 Wipro Technologies
Strings String functions
#include <stdio.h> #include <string.h> #include <stddef.h>
int main() { char string[] = "Words seperated by spaces -- and, punctuation!" char delimiters[] = " -,;:!_";
char *token, *cp; token = strtok(string, delimiters); while (token!=NULL) { printf("%s\n", token);; token = strtok(NULL, delimiters); } return 0; }
26
Copyright 2006 Wipro Technologies
Output: $ ./token Words seperated by spaces and punctuation
Thank You
Contact: [email protected] Or Unix FCG
Copyright 2006 Wipro Technologies