0% found this document useful (0 votes)
18 views

Using The STR Functions: Download Example 4

The document discusses common string manipulation functions in C including strcat(), strcpy(), strcmp(), and strlen(). It notes that these functions do not allocate memory, so when concatenating strings one must first allocate sufficient memory to store the combined string. As an example, it shows how to use malloc() to allocate space for the concatenated strings before copying and appending them.

Uploaded by

LoreineNealega
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Using The STR Functions: Download Example 4

The document discusses common string manipulation functions in C including strcat(), strcpy(), strcmp(), and strlen(). It notes that these functions do not allocate memory, so when concatenating strings one must first allocate sufficient memory to store the combined string. As an example, it shows how to use malloc() to allocate space for the concatenated strings before copying and appending them.

Uploaded by

LoreineNealega
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Using the str Functions

There are quite a number of these but you'll probably only need these that are listed below strcat() - concatenate two strings. strcpy() - copy a string (handy for doing string assignments). strcmp() - compare two strings. strlen() - return the length of a string- this does not include the terminating zero. strchr() - find a character in a string searching from left. You also get strn.. versions of the first three (not strlen( and strchr) with an extra parameter size_t n strncat(). strncpy(). strncmp(). These limit the operation to the first n chars. For instance strncat() appends a maximum of n chars from a string to another string. Memory Management You are responsible for making sure that strings are properly allocated and freed. For instance this string a="A very Long String"; string b=strcat(a," and now even longer!") ; While it looks ok is a guaranteed disaster. The first line executes fine but the second takes exception. The strcat() function does not allocate any memory. The compiler would perceive this text as being read-only so it's probably located somewhere that cannot be written to. In this case you must allocate enough space to store the combined strings. Example 4 demonstrates this correctly: Download #include #include #include Example 4. "stdlib.h" <stdio.h> <string.h>

typedef char * string; int main(int argc, char* argv[]) { string a="A very Long String"; string b=" and now even longer!"; string c=malloc(strlen(a) + strlen(b)+1) ; /* +1 DFTTZ! */ strcpy(c,a) ; strcat(c,b) ; printf("c = %s",c) ; free(c) ; return 0; }

You might also like