String and pointer

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”;

index012345678910
strtechaccess‘\0’
Address0x200x210x220x230x240x250x260x270x280x290x210

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)

string character value

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: