© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

3.  What is the difference between strings and character arrays?
 
A major difference is: string will have static storage duration, whereas as a character array will not, unless it is explicity specified by using the static keyword.
Actually, a string is a character array with following properties:

*   The  multibyte character sequence, to which we generally call string, is used to initialize an array of static storage duration. The size of this array is just sufficient to contain these characters plus the terminating NUL character.

*  It not specified what happens if this array, i.e., string, is modified.

*  Two strings of same value[1] may share same memory area. For example, in the following declarations:

char *s1 = “Calvin and Hobbes”;
char *s2 = “Calvin and Hobbes”;

the strings pointed by s1 and s2 may reside in the same memory location. But, it is not true for the following:

char ca1[] = “Calvin and Hobbes”;
char ca2[] = “Calvin and Hobbes”;

The value of a string is the sequence of the values of the contained characters, in order.

Ex - 1: What is the output?
  main()
{
char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}
Ans:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.

Ex - 2: What is the output?
main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Ans:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.   

Ex - 3: What is the output?

main()
{
      static int a[3][3]={1,2,3,4,5,6,7,8,9};
      int i,j;
      static *p[]={a,a+1,a+2};
            for(i=0;i<3;i++)
      {
                  for(j=0;j<3;j++)
                  printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
                  *(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
         }
}
Ans:
                  1       1       1       1
                  2       4       2       4
                  3       7       3       7
                  4       2       4       2
                  5       5       5       5
                  6       8       6       8
                  7       3       7       3
                  8       6       8       6
                  9       9       9       9
Explanation:

            *(*(p+i)+j) is equivalent to p[i][j].


SLogix Student Projects
bottom