Friday 20 January 2012

Built in functions in C

String Manipulation Functions


char *strcpy (char *dest, char *src); 
Copy src string into dest string.
char *strncpy(char *string1, char *string2, int n); 
Copy first n characters of string2 to stringl .
int strcmp(char *string1, char *string2); 
Compare string1 and string2 to determine alphabetic order.
int strncmp(char *string1, char *string2, int n); 
Compare first n characters of two strings.
int strlen(char *string); 
Determine the length of a string.
char *strcat(char *dest, const char *src); 
Concatenate string src to the string dest.
char *strncat(char *dest, const char *src, int n); 
Concatenate n chracters from string src to the string dest.
char *strchr(char *string, int c); 
Find first occurrence of character c in string.
char *strrchr(char *string, int c); 
Find last occurrence of character c in string.
char *strstr(char *string2, char string*1); 
Find first occurrence of string string1 in string2.
char *strtok(char *s, const char *delim) ;
Parse the string s into tokens using delim as delimiter.


Memory Management Functions

void *calloc(int num elems, int elem_size); 
Allocate an array and initialise all elements to zero .
void free(void *mem address);
Free a block of memory.
void *malloc(int num bytes); 
Allocate a block of memory.
void *realloc(void *mem address, int newsize); 
Reallocate (adjust size) a block of memory.

Buffer Manipulation



void* memcpy(void* s, const void* ct, int n);
Copies n characters from ct to s and returns s. s may be corrupted if objects overlap.
int memcmp(const void* cs, const void* ct, int n);
Compares at most (the first) n characters of cs and ct, returning negative value if cs<ct, zero if cs==ct, positive value if cs>ct.
void* memchr(const void* cs, int c, int n);
Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found.
void* memset(void* s, int c, int n); 
Replaces each of the first n characters of s by c and returns s.
void* memmove(void* s, const void* ct, int n); 
Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.

Tuesday 17 January 2012

C - memmove

Synopsis:
#include <stdio.h>
void* memmove(void* s, const void* ct, int n); 
Description:
Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.
Return Value
The memmove function returns s after moving n characters.
Example
#include <stdio.h>
int main() {
  static char buf [] = "This is line 1 \n"
                       "This is line 2 \n"
                       "This is line 3 \n";
  printf ("buf before = %s\n", buf);
  memmove (&buf [0], &buf [16], 32);
  printf ("buf after = %s\n", buf);
  return 0;
}
It will proiduce following result:
buf before = This is line 1
This is line 2
This is line 3
buf after = This is line 2
This is line 3
This is line 3

C - memset

Synopsis:
#include <stdio.h>
void* memset(void* s, int c, int n);
Description:
The memset function sets the first n bytes in s to c. Generally this function is used to set a memory location to null chracters '\0'.
Return Value
The memset function returns s with the set value to c
Example
#include <stdio.h>
int main() {
  char string[20];
  strcpy(string, "Hello");
  printf( "Before using memset |%s|\n", string );
  memset( string, '\0', sizeof(string) );
  printf( "After using memset |%s|\n", string );
  return 0;
}
It will proiduce following result:
Before using memset |Hello|
After using memset ||

C - memchr

Synopsis:
#include <stdio.h>
void* memchr(const void* cs, int c, int n);
Description:
The memchr function scans cs for the character c in the first n bytes of the buffer.
Return Value
The memchr function returns a pointer to the character c in cs or a null pointer if the character was not found.
Example
#include <stdio.h>
int main()
{
  char src [100] = "Search this string from the start";
  char *c;
  c = (char*)memchr (src, 'g', sizeof (src));
  if (c == NULL)
    printf ("'g' was not found in the src\n");
  else
    printf ("found 'g' in the src\n");
  return 0;
}
It will proiduce following result:
found 'g' in the src

C - memcmp function

Synopsis:
#include <stdio.h>
int memcmp(const void* cs, const void* ct, int n);
Description:
The memcmp function compares the first n bytes from cs and ct and returns a value indicating their relationship as follows:
Return Value
if Return value if < 0 then it indicates cs less than ct
if Return value if > 0 then it indicates ct is less than cs
if Return value if = 0 then it indicates cs is equal to ct
Example
#include <stdio.h>
int main()
{
  char hexchars [] = "0123456789ABCDEF";
  char hexchars2 [] = "0123456789abcdef";
  char i;
  i = memcmp (hexchars, hexchars2, 16);
  if (i < 0)
    printf ("hexchars < hexchars2\n");
  else if (i > 0)
    printf ("hexchars >  hexchars2\n");
  else
    printf ("hexchars == hexchars2\n");
  return 0;
}
It will proiduce following result:
hexchars < hexchars2

C - memcpy function

Synopsis:
#include <stdio.h>
void* memcpy(void* s, const void* ct, int n);
Description:
The memcpy function copies n bytes from ct to s. If these memory buffers overlap, the memcpy function cannot guarantee that bytes in ct are copied to s before being overwritten. If these buffers do overlap, use the memmove function.
Return Value
The memcpy function returns dest.
Example
#include <stdio.h>
int main()
{
  char src [100] = "Copy this string to dst1";
  char dst [100];
  char *p;
  p = memcpy (dst, src, sizeof (dst));
  printf ("dst = \"%s\"\n", p);
}
It will proiduce following result:
dst = "Copy this string to dst1"

Sunday 15 January 2012

Realloc function

Synopsis:
#include <stdio.h>
void *realloc(void *mem_address, int newsize); 
Description:
The size of the memory block pointed to by the mem_address parameter is changed to the newsize bytes, expanding or reducing the amount of memory available in the block.
In case that mem_address is NULL, the function behaves exactly as malloc, assigning a new block of newsize bytes and returning a pointer to the beginning of it.
In case that the newsize is 0, the memory previously allocated in mem_address is deallocated as if a call to free was made, and a NULL pointer is returned.
Return Value
A pointer to the reallocated memory block, which may be either the same as the mem_address argument or a new location.
Example
#include <stdio.h>
int main ()
{
  int input,n;
  int count=0;
  int * numbers = NULL;
  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;
     numbers = (int*) realloc (numbers, count * sizeof(int));
     if (numbers==NULL)
       { puts ("Error (re)allocating memory"); exit (1); }
     numbers[count-1]=input;
  } while (input!=0);
  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);
  return 0;
}
It will proiduce following result:
Enter an integer value (0 to end): 2
Enter an integer value (0 to end): 3
Enter an integer value (0 to end): 4
Enter an integer value (0 to end): 5
Enter an integer value (0 to end): 0
Numbers entered: 2 3 4 5 0

malloc function

Synopsis:
#include <stdio.h>
void * malloc ( int size );
Description:
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
Return Value
On success, a pointer to the memory block allocated by the function. If fails a NULL value is returned.
Example
#include <stdio.h>
int main ()
{
  int i,n;
  int * pData;
  printf ("Amount of numbers to be entered: ");
  scanf ("%d",&i);
  pData = (int*) malloc (i*sizeof(int));
  if (pData==NULL) exit (1);
  for (n=0;n<i;n++)
  {
    printf ("Enter number #%d: ",n);
    scanf ("%d",&pData[n]);
  }
  printf ("You have entered: ");
  for (n=0;n<i;n++) printf ("%d ",pData[n]);
  free (pData);
  return 0;
}
It will proiduce following result:
Amount of numbers to be entered: 10
Enter number #0: 2
Enter number #1: 3
Enter number #2: 3
Enter number #3: 4
Enter number #4: 5
Enter number #5: 6
Enter number #6: 7
Enter number #7: 8
Enter number #8: 3
Enter number #9: 9
You have entered: 2 3 3 4 5 6 7 8 3 9

free function

Synopsis:
#include <stdio.h>
void free(void *mem_address);
Description:
A block of memory previously allocated using a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
Return Value
None.
Example
#include <stdio.h>
int main ()
{
  int * buffer1, * buffer2, * buffer3;
  buffer1 = (int*) malloc (100*sizeof(int));
  buffer2 = (int*) calloc (100,sizeof(int));
  buffer3 = (int*) realloc (buffer2,500*sizeof(int));
  free (buffer1);
  free (buffer3);
  return 0;
}
It will proiduce following result:
This program has no output.
This is just demonstration of allocation and deallocation of memory.

Calloc Function

Synopsis:
#include <stdio.h>
void *calloc(int num elems, int elem_size); 
Description:
Allocates a block of memory for an array of number elements, each of them size bytes long, and initializes all its bits to zero.
Return Value
A pointer to the memory block allocated by the function.
Example
#include <stdio.h>
int main ()
{
  int i,n;
  int * pData;
  printf ("Amount of numbers to be entered: ");
  scanf ("%d",&i);
  pData = (int*) calloc (i,sizeof(int));
  if (pData==NULL) exit (1);
  for (n=0;n<i;n++)
  {
    printf ("Enter number #%d: ",n);
    scanf ("%d",&pData[n]);
  }
  printf ("You have entered: ");
  for (n=0;n<i;n++) printf ("%d ",pData[n]);
  free (pData);
  return 0;
}
It will proiduce following result:
Amount of numbers to be entered: 10
Enter number #0: 2
Enter number #1: 3
Enter number #2: 3
Enter number #3: 4
Enter number #4: 5
Enter number #5: 6
Enter number #6: 7
Enter number #7: 8
Enter number #8: 3
Enter number #9: 9
You have entered: 2 3 3 4 5 6 7 8 3 9

Thursday 12 January 2012

Strtok Function

Synopsis:
#include <stdio.h>
char *strtok(char *s, const char *delim) ;
Description:
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters spearated by any of the characters that are part of delimiters.
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in separator (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in separator, which becomes the end of the token.
This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
Example
#include <stdio.h>
int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}
It will proiduce following result:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string

Strstr Function

Synopsis:
#include <stdio.h>
char *strstr(char *string2, char string*1); 
Description:
The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence.
Return Value
The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in src a null pointer is returned.
Example
#include <stdio.h>
int main() 
{
   char s1 [] = "My House is small";
   char s2 [] = "My Car is green";
   printf ("Returned String 1: %s\n", strstr (s1, "House"));
   printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}
It will proiduce following result:
Returned String 1: House is small
Returned String 2: Car is green

Strrchr Functon

Synopsis:
#include <stdio.h>
char *strrchr(char *string, int c); 
Description:
The strrchr function searches string for the last occurrence of c. The null character terminating string is included in the search.
Return Value
The strrchr function returns a pointer to the last occurrence of character c in string or a null pointer if no matching character is found.
Example
#include <stdio.h>
int main() 
{
  char *s;
  char buf [] = "This is a testing";
  s = strrchr (buf, 't');
  if (s != NULL)
  printf ("found a 't' at %s\n", s);
  return 0;
}
It will proiduce following result:
found a 't' at ting

Strchr Function


Synopsis:
#include <stdio.h>
char *strchr(char *string, int c); 
Description:
The strchr function searches string for the first occurrence of c. The null character terminating string is included in the search.
Return Value
The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found.
Example
#include <stdio.h>
int main() 
{
  char *s;
  char buf [] = "This is a test";
  s = strchr (buf, 't');
  if (s != NULL)
  printf ("found a 't' at %s\n", s);
  return 0;
}
It will proiduce following result:
found a 't' at test

Strncat Functions


Synopsis:
#include <stdio.h>
char *strncat(char *dest, const char *src, int n); 
Description:
The strncat function concatenates or appends first n characters from src to dest. All characters from src are copied including the terminating null character.
Return Value
The strncat function returns dest.
Example
#include <stdio.h>
int main() 
{
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Returned String : %s\n", strncat( string1, string2, 4 ));
  printf("Concatenated String : %s\n", string1 );
  return 0;
}
It will proiduce following result:
Returned String : HelloHell
Concatenated String : HelloHell

Strcat Function


Synopsis:
#include <stdio.h>
char *strcat(char *dest, const char *src); 
Description:
The strcat function concatenates or appends src to dest. All characters from src are copied including the terminating null character.
Return Value
The strcat function returns dest.
Example
#include <stdio.h>
int main() 
{
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Returned String : %s\n", strcat( string1, string2 ));
  printf("Concatenated String : %s\n", string1 );
  return 0;
}
It will proiduce following result:
Returned String : HelloHellooo
Concatenated String : HelloHellooo

Strlen Function


Synopsis:
#include <stdio.h>
int strlen(char *src );
Description:
The strlen function calculates the length, in bytes, of src. This calculation does not include the null terminating character.
Return Value
The strlen function returns the length of src.
Example
#include <stdio.h>
int main()
{
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Length of string1 : %d\n", strlen( string1 ));
  printf("Length of string2 : %d\n", strlen( string2 ));
  return 0;
}
It will proiduce following result:
Length of string1 : 5
Length of string2 : 7

Strncmp Function


Synopsis:
#include <stdio.h>
int strncmp(char *string1, char *string2, int n); 
Description:
The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship.
Return Value
if Return value if < 0 then it indicates string1 is less than string2
if Return value if > 0 then it indicates string2 is less than string1
if Return value if = 0 then it indicates string1 is equal to string1
Example
#include <stdio.h>
int main() 
{
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 4));
  strcpy(string1, "Helloooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 10));
  strcpy(string1, "Hellooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 20));
  return 0;
}
It will proiduce following result:
Return Value is : 0
Return Value is : 111
Return Value is : 0

Strcmp Function

Description:
The strcmp function compares the contents of string1 and string2 and returns a value indicating their relationship.
Return Value
if Return value if < 0 then it indicates string1 is less than string2
if Return value if > 0 then it indicates string2 is less than string1
if Return value if = 0 then it indicates string1 is equal to string1
Example
#include <stdio.h>
int main() 
{
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  strcpy(string1, "Helloooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  strcpy(string1, "Hellooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  return 0;
}
It will proiduce following result:
Return Value is : -111
Return Value is : 111
Return Value is : 0

Strncpy Function

Synopsis:
#include <stdio.h>
char *strncpy (char *dest, char *src, int n);
Description:
The strcpy function copies n characters from src to dest up to and including the terminating null character if length of src is less than n.
Return Value
The strncpy function returns dest.
Example
#include <stdio.h>
int main()
{
  char input_str[20];
  char *output_str;
  strncpy(input_str, "Hello", 20);
  printf("input_str: %s\n", input_str);
  /* Reset string */
  memset(input_str, '\0', sizeof( input_str ));
  strncpy(input_str, "Hello", 2);
  printf("input_str: %s\n", input_str);
  /* Reset string */
  memset(input_str, '\0', sizeof( input_str ));
  output_str = strncpy(input_str, "World", 3);
  printf("input_str: %s\n", input_str);
  printf("output_str: %s\n", output_str);
  return 0;
}
It will proiduce following result:
input_str: Hello
input_str: He
input_str: Wor
output_str: Wor

Strcpy Function

char *strcpy (char *dest, char *src);
Synopsis:
#include <stdio.h>
char *strcpy (char *dest, char *src);
Description:
The strcpy function copies characters from src to dest up to and including the terminating null character.
Return Value
The strcpy function returns dest.
Example
#include <stdio.h>
int main() {
  char input_str[20];
  char *output_str;
  strcpy(input_str, "Hello");
  printf("input_str: %s\n", input_str);
  output_str = strcpy(input_str, "World");
  printf("input_str: %s\n", input_str);
  printf("output_str: %s\n", output_str);
  return 0;
}
It will proiduce following result:
input_str: Hello
input_str: World
output_str: World

Tuesday 10 January 2012

Functions in C

In programming, a big task is divided into smaller ones to enable programmers to develop on a solid foundation that others have done instead of starting over from scratch. In order to do so, function is invented in programming world. Proper functions hide its operation details from the external programs using them and expose only the interface and its usage.
Function is a block of statements which perform some specific task and always return single value to the calling function. Functions are used to minimize the repetition of code.
Some languages distinguish between functions which return variables and those which don't. C assumes that every function will return a value. If the programmer wants a return value, this is achieved using the return statement. If no return value is required, none should be used when calling the function.
There are two types of functions in c language.
1. Library Functions
A function which is predefined in c language is called library function printf(), scanf(), getch() etc are library functions
2. User Defined Functions
A function written by a programmer is called user defined function.
Example
#include
int add (int x, int y) {
int z;
z = x + y;
return (z);
}
main ()
{
int i, j, k;
i = 15;
j = 5;
k = add(i, j);
printf ("The value of k is %d\n", k);
}
Output
The value of k is 30
Scope of Function:
Only a limited amount of information is available within the body of each function. Variables declared within the calling function can't be accessed from the outside functions unless they are passed to the called function as arguments.
Global Variables:
A variable that is declared out side all functions is called Global variable. Global variables don't die on return from a function. Their value is retained, and is available to any other function in whole program.
Local Variables:
A variable that is declared within a function is called Local variable. They are created each time the function is called, and destroyed on return from the function. The values passed to the functions (arguments) are also treated like local variables.
Static Variables:
Static variables are like local variables but they don't die on return from the function. Instead their last value is retained, and it becomes available when the function is called again.

Monday 9 January 2012

Storage Classes in C

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
There are following storage classes which can be used in a C Program
1)auto
2)register
3)static
4)extern
auto - Storage Class
auto is the default storage class for all local variables.
{
            int Count;
            auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.
storage location- RAM
Default initial value- Garbage
Scope-local to block
lifetime-control within the block
register - Storage Class
register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).
storage location- CPU register
Default initial value- Garbage
Scope-local to block
lifetime-control within the block
{
            register int  Miles;
}
Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.
static - Storage Class
static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.
storage location- RAM
Default initial value- 0
Scope-local to block
lifetime-end of the block
static int Count;
        int Road;
        {
            printf("%d\n", Road);
        }
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitialized when the function is called. This inside a function static variable retains its value during vairous calls.
   void func(void);
   static count=10; /* Global variable - static is the default */
    main()
   {
     while (count--) 
     {
         func();
     }
    }
    void func( void )
   {
     static i = 5;
     i++;
     printf("i is %d and count is %d\n", i, count);
   }
    This will produce following result
    i is 6 and count is 9
    i is 7 and count is 8
    i is 8 and count is 7
    i is 9 and count is 6
    i is 10 and count is 5
    i is 11 and count is 4
    i is 12 and count is 3
    i is 13 and count is 2
    i is 14 and count is 1
    i is 15 and count is 0
NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memorize void as nothing. static variables are initialized to 0 automatically.
Definition vs Declaration : Before proceeding, let us understand the difference between defintion and declaration of a variable or function. Definition means where a variable or function is defined in realityand actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.
There is one more very important use for 'static'. Consider this bit of code.
   char *func(void);
   main()
   {
      char *Text1;
      Text1 = func();
   }
   char *func(void)
   {
      char Text2[10]="martin";
      return(Text2);
   }
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
    static char Text[10]="martin";
The storage assigned to 'text2' will remain reserved for the duration if the program.
extern - Storage Class
extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.
storage location- RAM
Default initial value- 0
Scope-global
lifetime-end of the block
When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files.
File 1: main.c
   int count=5;
   main()
   {
     write_extern();
   }
File 2: write.c
   void write_extern(void);
   extern int count;
   void write_extern(void)
   {
     printf("count is %i\n", count);
   }
Here extern keyword is being used to declare count in another file.
Now compile these two files as follows
   gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value.

Strings in C

Character type array is called string.All strings end with the NULL character.Use the %s placeholder in the printf() function to display string values.In other words to create a string in C you create an array of chars and set each element in the array to a char value that makes up the string. When sizing the string array you need to add plus one to the actual size of the string to make space for the null terminating character, "\0"
Declaration:
char name[50];


The above statement declares a string called name that can take up to 50 characters. It can be indexed just as a regular array as well.
name[] = {'t','w','o'};
Character  t  w o \0
ASCII Code 116 119 41 0
The last character is the null character having ASCII value zero.
n fact, C’s only truly built-in string-handling is that it allows us to use string constants (also called string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the \0 character. For example, we can declare and define an array of characters, and initialize it with a string constant:
        char string[] = "Hello, world!";
In this case, we can leave out the dimension of the array, since the compiler can compute it for us based on the size of the initializer (14, including the terminating \0). This is the only case where the compiler sizes a string array for us, however; in other cases, it will be necessary that we decide how big the arrays and other data structures we use to hold strings are.
To do anything else with strings, we must typically call functions. The C library contains a few basic string manipulation functions, and to learn more about strings, we’ll be looking at how these functions might be implemented.
Since C never lets us assign entire arrays,we use the strcpy function to copy one string to another.
Before starting programming with a String functions we should the include the following header file.
#include<string.h>
  • In C language Strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0' character:
  • It is important to preserve the NULL terminating character as it is how C defines and manages variable length strings. All the C standard library functions require this for successful operation.
  • All the string handling functions are prototyped in: string.h or stdio.h standard header file. So while using any string related function, don't forget to include either stdio.h or string.h. May be your compiler differes so please check before going ahead.
  • If you were to have an array of characters WITHOUT the null character as the last element, you'd have an ordinary character array, rather than a string constant.
  • String constants have double quote marks around them, and can be assigned to char pointers as shown below. Alternatively, you can assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!
char *string1 = "Hello";
char string2[] = "Hello";
char string3[6] = "Hello";
Functions in C
  • Strlen()
    size_t strlen ( const char * str );
    This function is used to find the length of the string.
  • strrev()This function is used to reverse the given string.
  • strcpy()
    char * strcpy ( char * destination, const char * source );
    This function is used to copy the string from one array variable to another array variable.
  • strcat()
    char * strcat ( char * destination, const char * source );
    This function is used to concatenation of two strings.  
  • strncpy()
    char * strncpy ( char * destination, const char * source, size_t num );
    This function of used to copy the string from source to destination but only a fixed n bytes is allowed to copy.
  • strncat()
    char * strncat ( char * destination, char * source, size_t num );
    This function of used to con-cat the string from source to destination but only a fixed n bytes is allowed to con-cat.
  • strcmp()
    int strcmp ( const char * str1, const char * str2 );
    Compares the C string str1 to the C string str2.
    This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
  • strcmpi() or stricmp()
    int strcmpi( const char *s1, const char *s2 );
    The strcmpi() function compares, with case insensitivity, the string pointed to by s1 to the string pointed to by s2. All uppercase characters from s1 and s2 are mapped to lowercase for the purposes of doing the comparison. The strcmpi() function is identical to the stricmp() function.
  • strrchr()const char * strrchr ( const char * str, int character );
          char * strrchr (       char * str, int character );
    Locate last occurrence of character in string
    Returns a pointer to the last occurrence of character in the C string str.
    The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.
  • memcmp()
    int memcmp ( const void * ptr1, const void * ptr2, size_t num );
    Compare two blocks of memory
    Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.
host gator coupon