A string is a sequence of characters terminated with a null(‘\0’) character. C does not have a string of data types. Basically, string is a one-dimensional array of characters.
For example, the string “techaccess” contains 11 characters including a null character added at the end by default by the compiler.
char str[] = “techaccess”;
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
str | t | e | c | h | a | c | c | e | s | s | ‘\0’ |
Address | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 | 0x25 | 0x26 | 0x27 | 0x28 | 0x29 | 0x210 |
A character array is a collection of variables that are of type “char”. It is a sequence of characters that are stored in consecutive memory locations.
The string itself acts as a pointer and the name of the string is a pointer to the first character in the string.
Please refer to the topics below for a clear understanding before reading further:
Example:
char str[11] = “techaccess”;
Where:
- str is the string name and it is a pointer to the first character (base address of an array) in the string, i.e. &str[0];
- Similarly, str + 1 holds the address of the second character in the string that is &str[1].
Sample Program:
Print each character of the string
#include <stdio.h>
int main ()
{
char str[11]= "techaccess"; // str is the base address
int i;
for (i = 0; str[i]; i++)
printf ("%c ", *(str + i));
return 0;
}
Output:
t e c h a c c e s s
Str[i] == *(str+i)
str[i] will give the character stored at the string index i.
str[i] is a shortend version of *(str+i).
*(str+i) – value stored at the memory address str+i. (base address + index)

Passing a string to a function and accessing each character:
#include <stdio.h>
void fun (char *str)
{
while(*str)
{
printf ("%c ", *str);
str++;
}
}
int main ()
{
char str[11]= "techaccess";
fun (str); //base address is passed to the function
return 0;
}
Output:
t e c h a c c e s s
Accessing string to a pointer:
# include <stdio.h>
int main ()
{
char str[11] = "techaccess"; //string name itself a base address of the string
char *ptr = str; //ptr references str
int i;
for ( i = 0; ptr[i]!= '\0'; i++)
printf ("%c ", *(ptr + i));
return 0;
}
Output:
t e c h a c c e s s
Accessing the string without pointer:
# include <stdio.h>
int main ()
{
char str[11] = "techaccess";
int i;
for ( i = 0; i <sizeof(str) ; i++)
printf ("%c ", (str[i]));
return 0;
}
Output:
t e c h a c c e s s
Accessing the complete string with %s specifier:
# include <stdio.h>
int main ()
{
char str[11] = "techaccess";
printf ("\n String is: %s ", str);
return 0;
}
Output:
String is: techaccess
Categories: C Language
Leave a Reply