Quick Navigation Bar dynamic memory allocation :: strings :: structures [ toc | forums ] |
Note: If the document URL does not begin with https://randu.org/tutorials/c/ then you are viewing a copy. Please direct your browser to the correct location for the most recent version. |
char str[5] = {'l', 'i', 'n', 'u', 'x'}; char str[6] = {'l', 'i', 'n', 'u', 'x', '\0'}; char str[3]; char str[ ] = "linux"; char str[5] = "linux"; char str[9] = "linux";All of the above declarations are legal. But which ones don't work? The first one is a valid declaration, but will cause major problems because it is not null-terminated. The second example shows a correct null-terminated string. The special escape character \0 denotes string termination. The fifth example also suffers the same problem. The fourth example, however does not. This is because the compiler will determine the length of the string and automatically initialize the last character to a null-terminator.
char *s; if ((s = malloc(sizeof(char) * 5)) == NULL) { /* ERROR Handling code */ } strcpy(s, "linux"); printf("%s\n", s);This would result in a bunch of junk being printed to the screen. printf will try to print the string, but will continue to print past the allocated memory for s, because there is no null-terminator. The simple solution would be to add 1 to the malloc call.
malloc
or realloc
in combination with strlen
.
strlen
returns the size of a string minus the
null-terminator. More on strlen on the next sub-section.char s1[ ] = "linux"; char *s2; strcpy(s2, s1);Remember that simply declaring a pointer does not create any space for the pointer to point to (remember that?).
size_t strlen(const char *s); char *strdup(const char *s); char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t n); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); int atoi(const char *nptr); double atof(const char *nptr);See Weiss pg. 486 (Appendix D.14) for a full string.h listing. Weiss Appendix D is your friend. Use it!
Notice: Please do not replicate or copy these pages and
host them elsewhere. This is to ensure that the latest version can always
be found here.
Disclaimer: The document author has published these pages
with the hope that it may be useful to others. However, the document
author does not guarantee that all information contained on these
webpages are correct or accurate. There is no warranty, expressed or
implied, of merchantability or fitness for any purpose. The author does
not assume any liability or responsibility for the use of the information
contained on these webpages.
If you see an error, please send an email to the address below indicating
the error. Your feedback is greatly appreciated and will help to
continually improve these pages.