***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Posts

    Thursday, November 26, 2020

    POINTERS AND STRINGS

    A string constant, like an array name by itself, is treated by the compiler as a pointer. Its value is the base address of the string.

    Consider the following code.

    char *p = “abc”;

    printf(“%s %s \n”, p, p + 1);    /* abc    bc is printed */

    The variable p is assigned the base address of the character array “abc”.

    When a pointer to char is printed in the format of a string, the pointed-at character and successive characters are printed until the end-of-string sentinel (that is, ‘\0’) is reached.

    Let us consider two declarations

    char *p = “abcde”; and char s[] = “abcde”;

    In the first declaration, the compiler allocates space in the memory for p, puts the string constant “abcde” in memory somewhere else, and initializes p with the base address of the string constant.

    The second declaration is equivalent to char s[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘\0’}; Because the brackets are empty, the complier allocates six bytes of memory for the array s.

     

    No comments:

    Post a Comment

    Top