Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Strings

String: It is an array of characters plus a marker that shows where our string
ends: the termination character (a binary zero character) \0.
We can create a string variable as an array of characters in the following way:

char first[] = "Hello,";


char second[] = "world";

The first line creates a string and assigns it the string value ”Hello”.
Another (a very inconvenient) way to do the same thing is

char first[] = {’H’,’e’,’l’,’l’,’o’,’,’,’\0’};

Note that ”nul” is not the same as ”NULL”.


The nul refers to a zero as defined by the escape sequence \0. It occupies one
byte of memory.
NULL is the name of the macro used to initialize null pointers.

1/1
#include <stdio.h>

char strA[80] = "A string to be used in this example";


char strB[80];

int main(void)
{
char *pA; /* a pointer to type character */
char *pB; /* another pointer to type character */
puts(strA); /* show string A */
pA = strA; /* point pA at string A */
puts(pA); /* show what pA is pointing to */
pB = strB; /* point pB at string B */
putchar(’\n’); /* move down one line on the screen */

while(*pA != ’\0’) /* line A */


{
*pB++ = *pA++; /* line B */
}
*pB = ’\0’; /* line C */
puts(strB); /* show strB on screen */
return 0;
}
2/1
The strlen() function from string.h is used for getting the length of a string.
A pointer version of strlen

/* strlen: return length of string s */


int strlen(char *s)
{
char *p = s;

while (*p != ’\0’)


p++;
return p - s;
}

3/1
int puts(const char *str)

from stdio.h writes a string to stdout;


the ”const” used as a parameter modifier informs the user that the function
will not modify the string pointed to by str, i.e. it will treat that string as a
constant

#include <stdio.h>

int main () {
char str1[15]="Programming2";
char str2[]="May";

puts(str1);
puts(str2);

return 0;
}

4/1
This program copies the contents of strA to strB.
#include <stdio.h>

char strA[80] = "A string to be used in this example";


char strB[80];

int main(void)
{
char *pA; /* a pointer to type character */
char *pB; /* another pointer to type character */
puts(strA); /* show string A */
pA = strA; /* point pA at string A */
puts(pA); /* show what pA is pointing to */
pB = strB; /* point pB at string B */
putchar(’\n’); /* move down one line on the screen */

while(*pA != ’\0’) /* line A */


{
*pB++ = *pA++; /* line B */
}
*pB = ’\0’; /* line C */
puts(strB); /* show strB on screen */
return 0;
} 5/1
The parameter passed to puts() is a pointer, and when we write puts(strA); as
we have seen, we are passing the address of strA[0];
when we write puts(pA) we are passing the same address, since we have set
pA = strA
Line A states: while the character pointed to by pA (i.e. *pA) is not a nul
character do the following:
Line B states: copy the character pointed to by pA to the space pointed to by
pB, then increment pA so it points to the next character and pB so it points to
the next space.
When we have copied the last character, pA now points to the terminating nul
character and the loop ends.
We add the nul character with line C.
exercise: Initialize
strB[80] = ”12345678901234567890123456789012345678901234567890”
and check what happens with strB

6/1
strcpy() from string.h copies a string

char *my_strcpy(char *destination, char *source)


{
char *p = destination;
while (*source != ’\0’)
{
*p++ = *source++;
}
*p = ’\0’;

return destination;
}

Using strcpy we can write the previuos program as follows

int main(void)
{
my_strcpy(strB, strA);
puts(strB);
}

7/1
In standard C strcpy would have the prototype:

char *my_strcpy(char *destination, const char *source);

The ”const” modifier is used to assure the user that the function will not
modify the contents pointed to by the source pointer.
exercise: Modify the function above, and its prototype, to include the ”const”
modifier as shown, and within the function add a statement which attempts to
change the contents of that which is pointed to by source, such as:
*source = ’X’;

*ptr++ again ,
It is to be interpreted as returning the value pointed to by ptr and then
incrementing the pointer value, that is ”read from left to right”.

The function
char *strncpy(char *dest, const char *src, size_t n)
from string.h copies up to n characters from the string pointed to, by src to
dest. If the length of src is less than that of n, the remainder of dest will be
padded with ’\0’.

8/1
More on strcpy() - this time with array notation

char *my_strcpy(char dest[], char source[])


{
int i = 0;
while (source[i] != ’\0’)
{
dest[i] = source[i];
i++;
}
dest[i] = ’\0’;
return dest;
}

The numerical value of the parameter passed is the same whether we use a
character pointer or an array name as a parameter, that is source[i] is the same
as *(source+i).

Other functions from string.h: strlen(); strcat(); strchr();


See string.h

9/1
heap string example:

/*
Given a C string, return a heap allocated copy of the string.
Allocate a block in the heap of the appropriate size,
copies the string into the block, and returns a pointer to the block.
The caller takes over ownership of the block and is responsible
for freeing it.
*/
char* StringCopy(const char* string) {
char* newString;
int len;

len = strlen(string) + 1; // +1 to account for the ’\0’


newString = malloc(sizeof(char)*len); // elemsize * numberofelements
assert(newString != NULL); // simplistic error check (a good habit)
strcpy(newString, string); // copy the passed in string to the block

return(newString); // return a ptr to the block


}

10 / 1
The StringCopy() function takes a C string, makes a copy of that string in the
heap, and returns a pointer to the new string. The caller takes over ownership
of the new string and is responsible for freeing it.
StringCopy() takes advantage of both of the key features of heap memory:
- size: StringCopy() specifies, at run-time, the exact size of the block
needed to store the string in its call to malloc(). Local memory cannot do
that since its size is specified at compile-time. The call to sizeof(char) is
not really necessary, since the size of char is 1 by definition. In any case,
the example demonstrates the correct formula for the size of an array
block which is element-size * number-of-elements.
- lifetime: StringCopy() allocates the block, but then passes ownership of it
to the caller. There is no call to free(), so the block continues to exist even
after the function exits. Local memory cannot do that. The caller will
need to take care of the deallocation when it is finished with the string.

11 / 1

You might also like