Assigning (String + Integer) to Variable : C Programming



In this typical question we are assigning (String + Integer) to variable of type character pointer. In this case starting address of the substring will be returned as a result.

Assigning (String + Integer) to Variable

Now guess the output of the following program

#include<stdio.h>

int main()
{
  char *str = "CProgramming";

  printf("\n%s", str + 0);
  printf("\n%s", str + 1);
  printf("\n%s", str + 2);
  printf("\n%s", str + 3);
  printf("\n%s", str + 4);
  printf("\n%s", str + 5);
  printf("\n%s", str + 6);
  printf("\n%s", str + 7);
  printf("\n%s", str + 8);
  printf("\n%s", str + 9);
  printf("\n%s", str + 10);
  printf("\n%s", str + 11);

return(0);
}

Output :

CProgramming
Programming
rogramming
ogramming
gramming
ramming
amming
mming
ming
ing
ng
g

Explanation

*str is pointer variable which is used to store the address of the character. In this example we have assigned the starting address of the string

Assigning (String + Integer) to Variable

lets assume the starting address of the string ‘CProgramming’ is 2000 then we can say following things –

Expression Return address Printed String
str + 0 2000 CProgramming
str + 1 2001 Programming
str + 2 2002 rogramming
str + 3 2003 ogramming
str + 4 2004 gramming
str + 5 2005 ramming
str + 6 2006 amming
str + 7 2007 mming
str + 8 2008 ming
str + 9 2009 ing
str + 10 2010 ng
str + 11 2011 g

Expression evaluation

Lets discuss how we obtain the output string when we print the expression containing sum of pointer and string

  1. str is pointer variable so address stored in the str would be address of character. i.e address of character 'C' in “CProgramming” string
  2. Initially value present inside the pointer variable is 2000.

As per pointer arithmetic –

str + 2 = (Starting address of 'str') + 2 * (Size of data type)
        = (Starting address of 'str') + 2 * (Size of character)
        = 2000 + 2 * 1
        = 2000 + 2
        = 2002

Recommended Article : Pointer arithmetic and Pointer addition

So we can say that str + 2 will return us address 2002 which is address of character 'r' so whenever we print a string using str + 2, we start printing the string from 'r'

Anonymous string + integer

#include<stdio.h>

int main()
{
  char *str = 1 + "CProgramming";

  printf("\n%s",str + 0);
  printf("\n%s",str + 1);

return(0);
}

Output :

Programming
rogramming

While assigning the value to pointer we have added the integer value with the string. In this case CProgramming is written inside the double quotes so anonymous pointer will have starting address of string CProgramming.

char *str = 1 + "CProgramming";

would assign the address of 'P' to the pointer variable instead of character 'C'.