Users Online

· Guests Online: 1

· Members Online: 1
Superadmin

· Total Members: 185
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

FAQ: C Character & Strings

FAQ (Frequently Asked Questions) >C Character & Strings
01 What is Type size_t in C?02 Explain NULL Character in C with Examples03 What is Difference Between a Character and a String in C?04 What is Difference Between Character Array and String Literal in C Language?
05 What is Difference Between Determining Length of a String and Character Array using sizeof Operator and strlen() Function in C Programming Language06 Explain Unrestricted and Length-Restricted String Functions in C with Examples07 What is Difference Between Basic and Advanced String Searching in C?08 Explain strtok() Function in C with Examples
09 How are Errors Reported When Operating System Fails to Perform some Requested Job in a C Program10 Explain Libc Functions Which Operate on Characters with Examples11 Explain Various Memory Functions in C with Examples12 Explain Command Line Arguments in C Programming with Examples
01 What is Type size_t in C?
Question: What is Type size_t in C?
Answer: Type of ‘size_t’ is what type sizeof operator returns. Standard C indicates that this is unsigned. But which unsigned is this? If it’s unsigned int or unsigned long. Let’s clear this out! Consider an example:

/* type_size_t.c -- program determines type of 'size_t' */
#include <stdio.h>
int main(void)
{
int byte_count;

printf("n*****Program shows type of size_t*****nn");
printf(""sizeof(size_t)" returns %d bytes.n", sizeof(size_t));

if (sizeof(size_t) == sizeof(unsigned long))
printf("nType of "size_t" is "unsigned long".nn");

/* Maximum value an `unsigned long int' can hold. (Minimum is 0)*/
# if __WORDSIZE == 64
# define ULONG_MAX 18446744073709551615UL
# else
# define ULONG_MAX 4294967295UL
# endif

return 0;
}

Observe below output of program on Linux Machine:

*****Program shows type of size_t*****

"sizeof(size_t)" returns 8 bytes.

Type of "size_t" is "unsigned long".
Actually, unsigned values can never be negative! So is type ‘size_t’ values. Several, string functions, like, strlen returns value of type ‘size_t’, strn– functions, like strncpy, strncat, strncmp etc. take one of their arguments as type ‘size_t’. Also, memory functions like memcpy, memmove, memset etc. each takes its 3rd argument as type ‘size_t’. Remember that type ‘size_t’ is treated as type unsigned long on Linux. But why do we need for type ‘size_t’? We’ll see this later.
Top
02 Explain NULL Character in C with Examples
This C Tutorial explains NULL Character in C with examples.
In C programming, character strings are terminated by NULL Byte. The representation for NULL Byte is ‘\0’ or ‘0’ (zero) or NULL. This way we wouldn’t be able to use NULL character in ours’ strings. Then why NULL character and not any other is used as a string terminator? Firstly, C doesn’t have explicit “string data type” and so how strings, an integral component, of everyday requirement to be handled? This requires to use some character to terminate the character arrays so the same could be treated as strings. Then which character? And why NULL character? The fact is NULL character doesn’t have any graphic printable symbol associated with it and consequently not required and this is why it’s used as a string terminator.

Recall that character strings and string literals are each terminated by NULL byte. String literal, however, doesn’t have visible NULL terminator. Compiler provides every string literal a NULL terminator while compiling the program. But character arrays may or may not contain NUL terminator. Character arrays which contain terminating NULL byte are strings. For example:

char season[] = {'a','u','t','u','m'}; /* character array */
char country[] = {'I','n','d','i','a','\0'}; /* character string */

char *str = "Hello, how are you?";
/* string literal: No visible NULL terminator */
Non-string data, however, can contain NULL characters. But string handling functions are particular with STRINGS and can’t deal with NON-STRING DATA. To process NON-STRING data, use memory functions instead.
Top
03 What is Difference Between a Character and a String in C?
Question: What is Difference Between a Character and a String in C?
Answer: A character is just a single character enclosed in single quotes. For example:

char initial = 'A'; /* initial declared to be a character */
And a character string is a sequence of 0 or more characters enclosed in double quotes. Each string is terminated by a NULL byte. Therefore, string containing 0 characters is called an empty string. For example,

char str[] = "hello, where are you these days?";
char empty_str[] = ""; /* empty string */
char *str_lit = "this is string literal";

Further, size of a character can be evaluated using sizeof operator while of strings, strlen function does so. strlen function returns actual no. of characters in the string excluding NULL byte. Therefore, while declaring a character array to be a string, keep one byte extra for NULL terminator plus size, in bytes, for maximum no. of characters in the string. For example, for a string containing maximum 10 characters, we need to declare character array of size 11 bytes, as:

char msg[11] = "hello dear"; /* 'msg' is 10 char string */
Notice that ‘msg’ is a 10 characters string while it’s declared and initialized to contain 11 characters. Last character is NULL byte to terminate the string ‘msg’. Let’s now take a simple program and observe its output.

/* diff_char_str.c -- program differentiates character and char string */
#include
#include

int main(void)
{
char initial = 'A'; /* initial initialized with character 'A' */
char str[] = "hello, where are you these days?";
char empty_str[] = ""; /* empty string */
char *str_lit = "this is a string literal";
char msg[11] = "hello dear"; /* 'msg' is 10 char string */

puts("n*****Program differentiates character and string*****n");
printf("Size of character '%c' is %d byten",
initial, sizeof(initial));
printf("Size of string "%s" is %d bytesn", str, strlen(str));
printf("Size of empty string "%s" is %d bytesn",
empty_str, strlen(empty_str));
printf("Size of string literal "%s" is %d bytesn",
str_lit, strlen(str_lit));
printf("Size of msg "%s" is %d bytesn", msg, strlen(msg));
puts("");
return 0;
}
Output of the above program as:

*****Program differentiates character and string*****

Size of character 'A' is 1 byte
Size of string "hello, where are you these days?" is 32 bytes
Size of empty string "" is 0 bytes
Size of string literal "this is string literal" is 22 bytes
Size of msg "hello dear" is 10 bytes
Notice that size of empty string is 0 bytes while of ‘msg’, which was declared to contain 11 characters, gives size as 10 bytes for string of 10 characters.


Top
04 What is Difference Between Character Array and String Literal in C Language?
Question: What is Difference Between Character Array and String Literal in C Language?
Answer: Let’s, first, consider following declarations,

#define STR_LIT "I'm string literal declared using #define"
char *str_lit = "I'm string literal declared through pointer-to-char";
char char_arr[5] = {'a','b','c','d','e'}; /* character array */
Let’s, now, embed them into a program below,

/*
* diff_chararr_strlit.c -- program differentiates char array and string
* literal
*/
#include
#define STR_LIT "I'm string literal declared using #define"

int main(void)
{
char *str_lit = "I'm string literal declared through pointer-to-char";
char char_arr[5] = {'a','b','c','d','e'}; /* character array */

puts("\n*****Program differentiates character array and "
"string literal*****\n");
puts(STR_LIT); /* add. of string literal passed to puts */
puts(str_lit);
puts("\n");
puts("Let's, now, try to access character array as character string..."
"\n");
puts(char_arr);
puts("\n");
return 0;
}

Output of above program when run on Linux Machine is as below,

*****Program differentiates character array and string literal*****

I'm string literal declared using #define
I'm string literal declared through pointer-to-char

Let's, now, try to access character array as character string...

abcde
So, what here you observed when accessed character array ‘char_arr as character string by passing its address to puts? Output contains all characters from the ‘char_arr’ with some extra unspecified characters appended in the end. How’s this? Actually, puts prints characters until it finds NULL terminator. Since, ‘char_arr’ wasn’t containing one therefore puts continued after the end of ‘char_arr’ until it found one. Then how to access character arrays? It’s easy, use loops with counter explicitly specifying no. of characters in character array. For example, to access ‘char_arr’,

for (i = 0; i < 5; i++)
putc(char_arr[i]); /* or printf("%c", char_arr[i]) */
String literals whether declared using #define statements or using pointer-to-char contain NULL bytes. In initialization

char *str_lit = "I'm string literal declared through pointer-to-char";
‘str_lit’ is a pointer to string “I’m string literal declared through pointer-to-char” wherever stored in memory. In string literals or string constants, there’s no visible NULL terminator. Compiler appends it with NULL terminator while compiling the program.

There’s one more basic difference between character array and string literal and that is string literals, like symbolic constants, are constant strings while character arrays aren’t.

Top
05 What is Difference Between Determining Length of a String and Character Array using sizeof Operator and strlen() Function in C Programming Language
Question: What is Difference Between Determining Length of a String and Character Array using sizeof Operator and strlen() Function in C Programming Language?

Answer: Let’s recall, firstly, concept of sizeof operator and strlen() functions before we implement them with character arrays or strings.

sizeof operator returns amount of memory allocated, in bytes, of the argument passed to it. It works with string as well as with non-string data. In particular, it works with any type of data. While strlen function works only with character strings. Undefined results when ‘Non-String’ data is passed to strlen. Let’s consider a C program to unravel the behaviour of these two functions.

Let’s write a C program to test working of sizeof and strlen functions with arrays and strings, for example:

/*
* diff_sizeof_strlen.c -- program shows differences between using sizeof
* and strlen with arrays and strings
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char char_arr[100] = {0}; /* 'char_arr' array string declared */
char str[100] = "strlen returns actual no. of characters in the string"
" but NULL byte";
int ranking[50]; /* 'ranking' an array of 50 integers */
float avg_marks[10]; /* 'avg_marks' an array of 10 floats */
char *str_lit = "I'm string literal declared and initialized using "
"ptr-to-char";

puts("\n**Program differentiates use of sizeof and strlen with arrays "
"and strings**\n");
puts("\nUsing sizeof...\n");
printf("Amount of mem. allocated to \"char char_arr[100]\" is %d "
"bytes.\n", sizeof(char_arr));
printf("Amount of mem. allocated to \"char str[100]\" is %d bytes.\n",
sizeof(str));
printf("Amount of mem. allocated to \"int ranking[50]\" is %d bytes."
"\n", sizeof(ranking));
printf("Amount of mem. allocated to \"float avg_marks[10]\" is %d "
"bytes.\n", sizeof(avg_marks));
printf("Amount of mem. allocated to \"char *str_lit\" is %d bytes.\n",
sizeof(str_lit));

puts("\nUsing strlen...\n");
printf("No. of characters returned in \"char char_arr[100]\" is %d."
"\n", strlen(char_arr));
printf("No. of characters returned in \"char str[100]\" is %d.\n",
strlen(str));
printf("No. of characters returned in \"int ranking[50]\" is %d.\n",
strlen(ranking));
printf("No. of characters returned in \"float avg_marks[10]\" is %d."
"\n", strlen(avg_marks));
printf("No. of characters returned in \"char *str_lit\" is %d.\n",
strlen(str_lit));
puts("");
return 0;
}

When above program compiled with warnings enabled, result is,

sizeof_stlen.c: In function ‘main’:
sizeof_stlen.c:23:2: warning: passing argument 1 of ‘strlen’ from
incompatible pointer type [enabled by default]
/usr/include/string.h:399:15: note: expected ‘const char *’ but argument
is of type 'int *’
sizeof_stlen.c:24:2: warning: passing argument 1 of ‘strlen’ from incompatible pointer type [enabled by default] /usr/include/string.h:399:15: note: expected ‘const char *’ but argument is of type ‘float *’ and when run with warnings allowed, resulted as:

**Program differentiates use of sizeof and strlen with arrays and strings**

Using sizeof...

Amount of mem. allocated to "char char_arr[100]" is 100 bytes.
Amount of mem. allocated to "char str[100]" is 100 bytes.
Amount of mem. allocated to "int ranking[50]" is 200 bytes.
Amount of mem. allocated to "float avg_marks[10]" is 40 bytes.
Amount of mem. allocated to "char *str_lit" is 8 bytes.

Using strlen...

No. of characters returned in "char char_arr[100]" is 0.
No. of characters returned in "char str[100]" is 66.
No. of characters returned in "int ranking[50]" is 5.
No. of characters returned in "float avg_marks[10]" is 6.
No. of characters returned in "char *str_lit" is 61.
Analysing the output below,

Function strlen has prototype as:

size_t strlen(char const*);

that is it handles character strings only. Further, it returns actual no. of characters in the string not counting on NULL. Notice char_arr[100] = {0} is allocated 100 bytes but returns 0 characters.
Top
06 Explain Unrestricted and Length-Restricted String Functions in C with Examples
This C Tutorial explains Unrestricted and Length-Restricted String Functions in C with examples.
Standard C library provides several string handling functions for performing various operations on strings. These functions are categorised into Length-Unrestricted and Length-Restricted functions. To use functions in a C program, include ‘‘ header which contains prototypes for both types of functions.

In general, Length-Unrestricted functions perform the specified operation like copy source string to destination, or concatenation of the source to the end of destination or to compare source and destination considering the full length of the source string. Let’s first focus on prototypes of functions,

char *strcpy(char *dst, char const *src);
/* strcpy copies 'src' to 'dst' */
char *strcat(char *dst, char const *src);
/* strcat concatenates 'src' to end of 'dst' */
int strcmp(char const *str1, char const *str2);
/* strcmp compares 'str1' and 'str2' */
Notice that strcpy and strcat functions return pointer to dst string while strcmp function returns an integer value.

In strcpy, if ‘src’ is longer than ‘dst’ array, it’ll copy ‘src’ into ‘dst’, overwrites whatever values happen to come after the ‘dst’ array in memory. Thus, overflowing the ‘dst’ array. Since, strcpy can’t determine if ‘dst’ array is long enough to hold the copy of ‘src’ string, it’s up to the programmer to ensure this. For ex.

/*
* srcstr_longer_dststr.c -- program shows what happens when copying larger
* 'src' str to shorter 'dst' str
*/
#include /* string functions prototype */
#include

int main(void)
{
char *src = "Hello, strcpy."; /* 'src' have 14 characters */
char dst[5]; /* 'dst' has 5 char */
char *copied;

copied = strcpy(dst, src);
printf("strcpy() returns \"%s\"\n", copied);
return 0;
}
Output is below:

strcpy() returns "Hello, strcpy."

In case if ‘src’ string is shorter than ‘dst’ array, ‘src’ string is copied into ‘dst’ array and old contents of ‘dst’ array are overwritten and lost. Old contents of ‘dst’ after the 1st NULL byte aren’t accessible and therefore of no practical importance.

strcat appends ‘src’ string to the end of ‘dst’ array. Therefore, it requires ‘dst’ array to be, at least, (possibly) empty string in case if it doesn’t have any characters. It copies the ‘src’ string and appends to the end of ‘dst’ array and returns a pointer to ‘dst’ array. Again, it’s up to the programmer to ensure that remaining space in ‘dst’ array should be long enough to hold the ‘src’ string. If it’s not the case, strcat runs off the end of the ‘dst’ array and writes into variables whichever happen to come after the ‘dst’ array in memory.

Let’s see an example program,

/*
* strcat.c -- program shows what happens when appending 'src' str to 'dst'
* str
*/
#include <stdio.h>
#include <string.h>
#define SIZE 25

int main(void)
{
char src[SIZE];
char quit[] = "quit";
char dst[SIZE] = ""; /* empty string */
char *cptr2dst;

puts("\n****Program appends source string to destination array****\n");
printf("User, type in a character string, this time not more than %d "
"characters long...,\nor \"quit\" to quit the program.\n", SIZE);
gets(src);
while (strncmp("quit", src, 4)) {
cptr2dst = strcat(dst, src);

printf("\n\nDestination string becomes \"%s\"\n", cptr2dst);
printf("And size, in bytes, of destination string is %d and %d "
"bytes remaining.\n\n", strlen(dst), SIZE - strlen(dst));

if (strlen(dst) > SIZE)
puts("\a\"DST OVERFLOWN!\"\a");

puts("\t\t\t***************\t\t\t\n");

printf("Want to append destination further, type in a new string "
not more than %d characters\nOr enter \"quit\" to terminate."
"\n\n", SIZE - strlen(dst));
gets(src);
}
puts("Bye! It's Interesting!\n");
return 0;
}
Observe the output below:

****Program appends source string to destination array****

User, type in a character string, this time not more than 25 characters
long..., or "quit" to quit the program.
okey, how's


Destination string becomes "okey, how's"
And size, in bytes, of destination string is 11 and 14 bytes remaining.

***************

Want to append destination further, type in a new string not more than 14
characters Or enter "quit" to terminate.

your


Destination string becomes "okey, how's your"
And size, in bytes, of destination string is 16 and 9 bytes remaining.

***************

Want to append destination further, type in a new string not more than 9
characters Or enter "quit" to terminate.

c prog


Destination string becomes "okey, how's your c prog"
And size, in bytes, of destination string is 23 and 2 bytes remaining.

***************

Want to append destination further, type in a new string not more than 2
characters Or enter "quit" to terminate.

ramming


Destination string becomes "okey, how's your c programming"
And size, in bytes, of destination string is 30 and -5 bytes remaining.

"DST OVERFLOWN!"
***************

Want to append destination further, type in a new string not more than -5
characters Or enter "quit" to terminate.

quit
Bye! It's Interesting!
Notice that strcat doesn’t care for if ‘dst’ has enough room for new string to be appended. It just appends and runs off the end of ‘dst’ writing into locations whatever be after the ‘dst’ in memory.

Now, turn to strcmp function which compares two strings to their corresponding characters and return 0 if two are same or negative value if first string is lower than second or positive when second string is higher than first. Let’s take an example,

/*
* strcmp.c -- program shows how two strings str1 and str2 compared and
* return int value
*/
#include
#include
#define SIZE 5

int main(void)
{
char str1[SIZE];
char str2[SIZE];
int ret;

puts("\n*****Program compares two strings in full lengths*****\n");
printf("Enter first string not more than %d characters or \"quit\" to "
"Quit.\n", SIZE);
gets(str1);

while (strncmp("quit", str1, 4)) {
printf("\nEnter second string not more than %d characters\n", SIZE);
gets(str2);

if ((ret = strcmp(str1, str2)) == 0)
puts("\nTwo strings are SAME.");
else if ((ret = strcmp(str1, str2)) < 0)
puts("\nString first is Lower than second.");
else
puts("\nSecond string is Lower than first.");

puts("\t\t\t*****************\t\t\t");
printf("Want to continue...\nEnter first string not more than %d "
"characters or \"quit\" to Quit.\n", SIZE);
gets(str1);
}
printf("\nBye!\n");
return 0;
}
Output as under:

*****Program compares two strings in full lengths*****

Enter first string not more than 5 characters or "quit" to Quit.
awake

Enter second string not more than 5 characters
drake

Strings first is Lower than second.
*****************
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
mello

Enter second string not more than 5 characters
mello

Two strings are SAME.
*****************
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
hello

Enter second string not more than 5 characters
zello

Strings first is Lower than second.
*****************
Want to continue...
Enter first string not more than 5 characters or "quit" to Quit.
quit

Bye!
Let’s consider prototypes of Length-Restricted String functions,

char *strncpy(char *src, char const *dst, Size_t len);
char *strncat(char *src, char const *dst, size_t len);
int strncmp(char const *str1, char const *str2, size_t len );
strncpy copies ‘len’ bytes from ‘src’ to ‘dst’, strncat appends ‘len’ bytes from ‘src’ to the end of ‘dst’ and strncmp compares ‘len’ bytes of ‘str1’ and ‘str2’.

Top
07 What is Difference Between Basic and Advanced String Searching in C?
Question: What is Difference Between Basic and Advanced String Searching in C?
Answer: ANSI C provides several string functions for locating characters, any of a group of characters or locating and extracting individual sub-strings in a given string. Let’s consider, firstly, basic string searching functions,

Finding a character: To locate a single character with its leftmost or rightmost occurrence in a given string, strchr and strrchr functions are prototyped below:

char *strchr(const char *str, int ch);
char *strrchr(const char *str, intch);
strchr returns pointer to leftmost occurrence of character if it’s found otherwise retuns NULL. strrchr returns location of rightmost occurrence of character if it’s found else returns NULL. For example:

char *loc1;
char *loc2;

-----
loc = strchr("how's your C programming project.", 'p');
loc = strrchr("how's your C programming project.", 'p');
‘loc1’ now points to character ‘p’ in programming in first argument while ‘loc2’ points to character ‘p’ in project in first argument.

Finding any of several characters: In order to locate any of several characters in the given string from the group string, function strpbrk is prototyped below:

char *strpbrk(const char *, const char *);
For example:

/*
* strpbrk.c -- strpbrk locates first occurrence of any of several
* characters from group string in a given string otherwise returns NULL
*/
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str = "how's your C programming project?";
char *gstr = "interesting";
char *loc;

loc = strpbrk(str, gstr);
printf("\nptr-to-char \"loc\" points to first occurrence of character "
"\'%c\'\nat %d location in the string \"%s\"\n\n",
*loc, loc - str, str );

return 0;
}

Output of above program

ptr-to-char "loc" points to first occurrence of character "s"
at 4 location in the string "how's your C programming project?"
Now, here’s arising naturally a question on how to find the rightmost occurrence of any of several characters from the group string into a given string? In fact, we haven’t any such string function in C library. But we can write one using strchar function. Wouldn’t it be interesting you give a try to it yourself?

Finding a sub-string in a given string: strstr function searches for leftmost occurrence of the given sub-string in its entirety into the given string and returns pointer to it once found otherwise returns NULL. For example:

/*
* strstr.c -- function strstr returns leftmost location of sub-string in a
* given 1st argument else NULL
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char str[100];
char substr[50];
char *loc;

puts("*****Program returns location of leftmost occurrence of "
"sub-string in the given string else returns NULL*****");
puts("");

puts("User, type in a string...");
gets(str);
puts("");

puts("now, type in a sub-string...");
gets(substr);
puts("");

/* Let's find sub-string */
loc = strstr(str, substr);
if (loc != NULL)
printf("leftmost occurrence of sub-string in a given string is at "
"location %d.\n\n", (loc - str) + 1);
else
printf("sub-string not found.\n\n");
return 0;
}
Output is as follows:

*****Program returns location of leftmost occurrence of sub-string in the
given string else returns NULL*****

User, type in a string...
twinkle twinkle little star

now, type in a sub-string...
twinkle

leftmost occurrence of sub-string in a given string is at location 1.

User, type in a string...
twinkle twinkle little star

now, type in a sub-string...
wonder

sub-string not found.
Notice that strstr returns location of leftmost occurrence of sub-string in a given string else returns NULL. Then, what about rightmost occurrence of sub-string in a given string? That is strrstr! We don’t have such in C library. Won’t you like to try this?

Let’s now turn to take more advanced string searching functions and explore them here. We prototype two such functions below:

size_t strspn(const char *str, const char *gstr);
size_t strcspn(const char *str, const char *gstr);
Notice the type of two functions which is type ‘size_t’ i.e. each function returns an unsigned value. Let’s differentiate them. For example,

/*
* strspn.c -- program returns no. of characters in the beginning of 1st
* argument that match any of characters in the 2nd argument
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char str[100];
char group[100];
size_t char_count;

puts("****Program returns no. of characters at the beginning of string "
"that match\n\tany of characters in group string.****");
puts("");

puts("User, type in a string...");
gets(str);
puts("");

puts("now, type in group string...");
gets(group);
puts("");

/* Let's count characters */
char_count = strspn(str, group);
printf("%d characters at the beginning of string matched.\n",
char_count);
puts("");
return 0;
}
Output of the strspn.c is below:

****Program returns no. of characters at the beginning of string that match
any of characters in group string.****

User, type in a string...
C requires very strong pointer concepts.

now, type in group string...
C is just pointers

4 characters at the beginning of string matched.

User, type in a string...
then how you feel with pointers? Are you okay with them?

now, type in group string...
Hmmm!

0 characters at the beginning of string matched.
Notice that strspn returns no. of characters from the start of the string which match any of the characters in group string. When 1st character of string doesn’t match any character in the group, function returns 0.

Let’s consider example of strcspn function below:

/*
* strcspn.c -- program returns max length of initial segment of first
* argument which comprises of characters not entirely from 2nd argument
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
char str[100];
char gstr[100];
size_t len_ini_seg;

puts("\n*****Program returns max initial segment of string without any "
"characters from group string*****");
puts("");

puts("User, type in a string...");
gets(str);
puts("");

puts("now, type in group string...");
gets(gstr);
puts("");

/* Let's call strcspn */
len_ini_seg = strcspn(str, gstr);
printf("%d characters at the beginning of string NOT matched any of "
"characters in group string.\n", len_ini_seg);
return 0;
}
Output is as under:

*****Program returns max initial segment of string without any characters
from group string*****

User, type in a string...
where are you going this time?

now, type in group string...
xyz

10 characters at the beginning of the string NOT matched any of characters
in group string.

User, type in a string...
i don't understand what do you mean...

now, type in group string...
i, i, hmmm...

0 characters at the beginning of the string NOT matched any of characters
in group string.
Notice that strcspn function behaves opposite to strspn function. It counts on characters from the start of the string which don’t match any characters in the group string.


Top
08 Explain strtok() Function in C with Examples
This C Tutorial explains strtok() string function in C programming with examples.
Strings in C comprise of individual parts separated by one or more characters called delimiters. These individual parts are called tokens. In order to process these individual parts, they have to be extracted from the string. That’s what strtok() function does. Empty string doesn’t have any tokens.

strtok() isolates these parts, discards the delimiters and NULL terminate them. Function is prototyped below:

char *strtok(char *str, const char *delimiters);
Let’s understand how strtok() works. A sequence of calls to strtok() breaks the string pointed to by ‘str’ into a sequence of tokens, each of which is delimited by a byte from the string pointed to by delimiters. The first call in the sequence has ‘str’ as its first argument, and is followed by calls with a null pointer as their first argument. The separator string pointed to by delimiters may be different from call to call.

The first call in the sequence searches the string pointed to by ‘str’ for the first byte that is not contained in the current separator string pointed to by delimiters. If no such byte is found, then there are no tokens in the string pointed to by ‘str’ and strtok() shall return a null pointer. If such a byte is found, it is the start of the first token.

The strtok() function then searches from there for a byte (or multiple, consecutive bytes) that is contained in the current separator string. If no such byte is found, the current token extends to the end of the string pointed to by ‘str’, and subsequent searches for a token shall return a null pointer. If such a byte is found, it is overwritten by a null byte, which terminates the current token. The strtok() function saves a pointer to the following byte, from which the next search for a token shall start.

Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above. Then function prototype becomes as:

char *strtok(NULL, const char *delimiters);
Because the strtok() functions parses the string passed to it, it modifies the string. Therefore, in order string must not be changed, copy the string and pass copy as an argument. Remember, don’t copy the address and pass the same. Instead, copy the entire string and pass it as an argument. Let’s take an example:

/* strtok.c -- program finds and extracts tokens in a given string */

#include <stdio.h>
#include <string.h>

int main(void)
{
char str[100];
char delimiters[] = " \t\n\v\f\r"; /* possible space delimiters */
char *token;

puts("\n**Program extracts Tokens and displays them One per Line.**\n");
puts("User, enter a string...");
gets(str);

/* let's parse the string */
for (token = strtok(str, delimiters); token != NULL;
token = strtok(NULL, delimiters)) /* 'for loop' conditional part */
/* prints token one per line */
puts(token);

return 0;
}

Output as follows:


**Program extracts Tokens and displays them One per Line.**

User, enter a string...
strtok() isolates tokens from the string

strtok()
isolates
tokens
from
the
string
[root@localhost ch09_StringsCharactersAndBytes]# ./strtok

**Program extracts Tokens and displays them One per Line.**

User, enter a string...


[root@localhost ch09_StringsCharactersAndBytes]# ./strtok

**Program extracts Tokens and displays them One per Line.**

User, enter a string...
Notice that strtok(), in its first input, parsed the given string into tokens and displayed them one/line. When input was an empty string or was comprising entirely with characters from delimiters string, it returned NULL. Since NULL doesn’t have graphical symbol associated with it, it’s not printed.

Top
09 How are Errors Reported When Operating System Fails to Perform some Requested Job in a C Program
Question: How are Errors Reported When Operating System Fails to Perform some Requested Job in a C Program?
Answer: In fact, we write C programs and request, for example, open a file for writing into it, to execute a some command etc., with Operating System and O.S., then, attempts to perform the requested work for us. What happens if O.S. fails to perform? Some error occurs. How’s this error reported to the user? Error, if any, occurs is reported to user by setting an external integer variable called ‘errno’ to an error code. The stderr() takes one of these error codes as an argument and returns a pointer to a massage describing the error. The function is prototyped below:

char *strerr(int errno);

Let’s now consider a simple program,

/* strerr.c -- program shows a pretty easy implementation of strerr() */
#include <stdio.h>
#include <string.h>
int main(void)
{
int errno = 0; /* errno set to 0 */

/* series of 'puts' calls */
puts("Let's");
puts("check");
puts("the");
puts("behaviour");
puts("of");
puts("strerr()");
puts("function.");

fprintf(stderr, "\nputs STATUS: %s\n", strerror(errno));
return 0;
}
Output is as follows:

Lets
check
the
behaviour
of
strerr()
function.

puts STATUS: Success
Notice that above program succeeded! However, there are chances that program fails for some errors. In general, the best way to detect the errors is to test the return values of functions.


Top
10 Explain Libc Functions Which Operate on Characters with Examples
Question: What are Different Functions in libc Which Operate on Characters?
Answer: C library provides two groups of functions which operate on characters and these are prototyped in header . Two groups are:

1. Character classification functions
2. Character transformation functions

Character classification functions, for example,

int islower(int);
int isupper(int);
int iscntrl(int);
int isdigit(int);
int isxdigit(int);
int isspace(int);
int ispunct(int);
int isalpha(int);
int isalnum(int);
int isgraph(int);
int isprint(int);
classify the argument which is an integer containing character value. And function returns an integer, 0 or non-zero value for false and true respectively. Since standard doesn’t give a specified value, any non-zero value is considered true. For example,

char ch1 = 'A', ch2 = '7';

isupper(ch1); /* checks if 'ch1' is upper case character */
isdigit(ch2); /* tests if 'ch2' is a decimal digit */
Notice here that isupper(ch1) returns true if ‘ch1’ is upper case character else returns false. Similarly, isdigit(ch2) returns true if ‘ch2’ is a decimal digit else returns false. This way each classification function works.

Let’s, now, consider character transformation functions, for example,

int toupper(int);
int tolower(int);
Transformation functions translate upper case characters to lower case and vice versa. toupper() returns upper case equivalent of its argument and tolower() returns lower case equivalent of its argument. If argument to either function is not a character of appropriate case, then it’s returned unchanged.

For example, If in some situation, you need to test a given character, say ‘ch’, is an upper case alphabet, then write test case as,

char ch = 'g';

if (isupper(ch))
----;
rather than

if (ch >= 'A' && ch <= 'Z')
----;

First test case is portable with any ‘Character Set’ so it executes correctly.

Let’s consider an interesting program below,

/* char_operations.c -- program manipulates characters */
#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
int i;
char *str;

puts("\n**Program transforms character strings on cmd-line**\n");
for (i = 0; i < argc; i++) {
str = argv[i];
if (i % 2 == 0) {
/* convert string into upper case */
while (*str)
putchar(toupper(*str++));

puts("");
}
else if (i % 2 == 1) {
/* convert string into lower case */
while (*str)
putchar(tolower(*str++));

puts("")
}
}
return 0;
}
Output is as below:

[root@localhost ch09_StringsCharactersAndBytes]# gcc -o char_operations
char_operations.c
[root@localhost ch09_StringsCharactersAndBytes]# ./char_operations
"converting lower case characters to upper case"
"and upper case characters to lower case alternatively" "thank you"

**Program transforms character strings on cmd-line**

./CHAR_OPERATIONS
converting lower case characters to upper case
AND UPPER CASE CHARACTERS TO LOWER CASE ALTERNATIVELY
thank you


Top
11 Explain Various Memory Functions in C with Examples
This C Tutorial explains Different Memory Functions in C and Explain Their Use with Examples.
String handling functions, as we have seen, deal only with string-data. Then what about the processing of Non-String data, for example, an array of floats, an array of structures, an array of pointers etc.. Further, it’s not uncommon for non-string data to contain’0′ (NULL) characters. ANSI C library provides a related set of functions called memory functions for handling such needs.

Let’s consider the prototypes of some of the most common memory functions below,

void *memcpy(void *dst, const void *src, size_t lenbytes);
void *memmove(void *dst, const void *src, size_t lenbytes);
void *memcmp(void const *dst, const void *src, size_t lenbytes);
void *memchr(void const *a, int ch, size_t lenbytes);
void *memset(void *a, int ch, size_t lenbytes);
Notice the type of arguments ‘void *’ in function prototypes which means pointers-to-any_type can be passed to pointers of type ‘void *’. In addition, unlike strn— functions, memory functions don’t stop when they encounter the first NULL character. These functions deal with arbitrary sequences of bytes. Let’s take examples to understand them well,

char msg[] = "tomorrow's sunday, we gonna out for picnic!";
char dst[100];
size_t nbytes;

memcpy(dst, msg, sizof(msg)); /* copies the entire 'msg' to 'dst' */
memcpy(dst, msg, 20); /* copies 20 bytes from 'msg' to 'dst' */
What happens if we try to copy an array of ‘ints’, for example,

int num[15] = {1,0,5,6,7,12,87,34,98,111,90,345,09,689,1};
int dst[15];

memcpy(dst, num, sizeof(num)); /* entire 'num' copied into 'dst' */
What if part of ‘num’ to be copied, for ex. 6 elements, then multiply the count by size of one element as:

memcpy(dst, num, 6 * sizeof(num[0]));
There’s a drawback associated with memcpy() which is while copying if source array and destination array overlaps in some way, result is undefined. memmove() is best choice if there’s any possibility of overlapping of source and destination array. Consider a program,

/*
* memcpy_memmove.c -- program copies specified bytes from source array to
* 'dst' array
*/
#include
#include

void show_val(const int [], int);

int main(void)
{
int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
int target[SIZE];
double dval[SIZE / 2]= {1.0,2.0,3.0,4.0,5.0};
int i;

printf("Original Array \'val\' of integers is: ");
show_val(val, SIZE);
puts("\n");

puts("memcpy(): copying array of ints \'val\' to array of ints "
"\'target\'");
memcpy(target, val, SIZE * sizeof(val[0]));
printf("target becomes: ");
show_val(target, SIZE);
puts("\n");

puts("memmove(): copying range 0-5 of \'val\' to 2-7 of \'target\'");
memmove(target + 2, val, 5 * sizeof(val[0]));
printf("target becomes: ");
show_val(target, SIZE);
puts("\n");

puts("memcpy(): copying array of 5 doubles to array of 10 ints");
memcpy(val, dval, (SIZE / 2) * sizeof(dval[0]));
puts("Array of ints \'val\' becomes: ");
show_val(val, SIZE);
puts("\n");

return 0;
}
Output is as follows:

Original Array 'val' of integers is: 1 2 3 4 5 6 7 8 9 10

memcpy(): copying array of ints 'val' to array of ints 'target'
target becomes: 1 2 3 4 5 6 7 8 9 10

memmove(): copying range 0-5 of 'val' to 2-7 of 'target'
target becomes: 1 2 1 2 3 4 5 8 9 10

memcpy(): copying array of 5 doubles to array of 10 ints
Array of ints 'val' becomes:
0 1072693248 0 1073741824 0 1074266112 0 1074790400 0 1075052544
Notice that we, in the last case in above program, copied doubles to ints. Actually, memcpy() and memmove() functions don’t know the type of arguments, just copies byte by byte. we can, this way, copy values of any type to any type, for ex. we can copy array of structures to array of characters.

memcmp(): memcmp() function works exactly like strcmp() except that it takes arguments of type ‘void *’. Therefore, we can use memcmp() to compare array of ints, array of structures etc. For ex.

/*
* memcmp.c -- program compares specified bytes as unsigned bytes from
* source array to 'dst' array
*/
#include <stdio.h>
#include <string.h> /* for memory fun. prototypes */
#define SIZE 10
void show_val(int [], int);

int main(void)
{
char dear[] = "u want to learn C programming.";
char sure[] = "u want to learn, sure!";
int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
int target[SIZE] = {1,2,3,4,5};

puts("character strings \'dear\' and \'sure\' are as:");
puts(dear);
puts(sure);
puts("");

puts("Let's compare \'dear\' and \'sure\'");
if (memcmp(sure, dear, 15) == 0)
/* first 15 bytes */
puts("First 15 bytes of \'sure\' and \'dear\' Matched.\n");

puts("Arrays of ints \'val\' and \'target\' are as:");
printf("val: ");
show_val(val, SIZE);
printf("target: ");
show_val(target, SIZE);
puts("");

puts("Let's compare \'val\' and \'target');
if (memcmp(target, val, 5 * sizeof(int)) == 0)
/* first 5 ints */
puts("First 5 integers in \'val\' and \'target\' Matched.\n");

return 0;
}

void show_val(int copy[], int n)
{
int i;

for (i = 0; i < n; i++)
printf("%2d ", copy[i]);

puts("");
}

Output of the program as:

character arrays 'dear' and 'sure' are as:
u want to learn C programming.
u want to learn, sure!

Let's compare 'dear' and 'sure'
First 15 bytes of 'sure' and 'dear' Matched.

Arrays of ints 'val' and 'target' are as:
val: 1 2 3 4 5 6 7 8 9 10
target: 1 2 3 4 5 0 0 0 0 0

Let's compare 'val' and 'target'

First 5 integers in 'val' and 'target' Matched.
memcmp() compares specified bytes in byte-by-byte manner as unsigned character bytes and returns 0 if two arrays are same or negative value if first argument is lower than second and positive value when first argument is higher than second.

memchr(): function searches specified bytes beginning at location specified by first argument for the first occurrence of character ‘ch’ and returns pointer to that location. If character doesn’t found, NULL is returned.

memset(): function sets specified bytes beginning at location specified by first argument a with the character ‘ch’ given as 2nd argument returns pointer to first argument. For ex.

int val[SIZE] = {1,2,3,4,5,6,7,8,9,10};
memset(val, 0, 5 * sizeof(int));

val becomes: 0 0 0 0 0 6 7 8 9 10


Top
12 Explain Command Line Arguments in C Programming with Examples
This C Tutorial explains Command Line Arguments in C Programming with examples.
Linux system gives us a command environment where we execute commands to perform certain tasks. For example,

ls command lists files and directories in a directory
ll gives long listing of files and directories in a directory
Actually, such commands are programs. And we may or may not pass arguments to programs for specific needs.

How can we pass arguments to ours’ C programs? Well! We can pass arguments to a C program through command environment. These arguments go into program’s main() parameters. A C program’s main takes generally two arguments, these are, first an integer type and the other an array of pointers-to-char.

int main(int argc, char *argv[])
{
/* statements */
}
argc stands for argument’s count while argv contains argument values. These names haven’t any magic associated with them and you can use any of yours’ choice for them. argv[] array is terminated by a NULL string. Therefore, you can use either of two arguments to count on no. of arguments passed to a C program.

Consider the below given command, say, to compile a program named “cmd.c”,

gcc -o cmd cmd.c
./cmd -abc -def hello, command line" "you pass arguments to program"
"great"
Firstly, we compiled cmd.c to a binary file with name cmd then we run the binary file cmd together with several arguments. All the arguments including program name, any options beginning with dash ‘-‘ followed by strings are passed into main’s parameters of cmd.c. Arguments passed from the command into a program are called command-line arguments. Let’s see a simple C program processing command-line arguments,

int main(int argc, char *argv[])
{
while (*argv != NULL) {
printf("%s", *argv);
argv++;
}

return 0;
}
Notice that above program doesn’t do useful except it prints on the terminal arguments passed to it with the program name.

Top
Render time: 0.34 seconds
7,458,465 unique visits