Strings Are One-Dimensional Arrays of Type Char

Total Page:16

File Type:pdf, Size:1020Kb

Strings Are One-Dimensional Arrays of Type Char

Strings •Strings are one-dimensional arrays of type char •A string in C is terminated by the end-of-string sentinel \0, or null character •Like with all arrays, it is the job of the programmer to make sure that string boundaries are not overrun.

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

 “abc” is a character array of size 4 with the last element being null character \0

 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, each successive characters in the array are printed until the end-of string sentinel is reached.

Example II: char * p=”abcd”; and char s[ ]=”abcd”;

In the first declaration the compiler allocates space in memory for p, puts the sting constant “abcd” in memory, and inilializes p with the base address of the string. Basically p is pointing to the string.  In the second declaration, the compiler allocates 5 bytes of memory for the array s. The first byte is initialized with ‘a’, the second with ‘b’ …and fifth one with a null character \0 .

Recommended publications