Strings
- Strings are nothing but an array of characters - there is no primitive
string
type in C. - Special null character
'\0'
needed at the end of every string -
"string literal"
is legal, compiler will make aconst
array of chars to hold it for you. - No string
+
concatenation like in Java or Python -
#include <string.h>
to access library functions; Reference forstring.h
functions -
strlen(s)
returns number of chars before'\0'
String library functions
- These functions show off pointers and
const
well - They use pointer types
char *
for strings, not array typeschar []
- Memory must previously be allocated by you if you are passing a reference where the function will put a result.
- The functions use
const
to indicate arguments they don't change
stdlib.h
string conversion functions
-
double atof(const char *s)
-
int atoi(const char *s)
-
double strtod(const char *s, char **endp)
stdio.h
string i/o functions
-
puts(s)
-
gets(s)
- very insecure, don't use - may overwrite memory not allocated to your program! -
fgets(s, MAXSIZE, stdin)
- use this instead; must allocate memory for s first!
Common string.h
string manipulation functions
-
strlen(const char *str)
- length of string -
char *strcpy(char *dest, const char *orig)
- copy from string
orig
to stringdest
- return
dest
-
strncpy(dest, orig, howmany)
only copieshowmany
characters -
char *strcat(char *orig, const char *more)
- concatenate
more
to end oforig
(orig = orig + more) - return
orig
- concatenate
-
int strcmp(const char *s1, const char *s2)
- compare
s1
tos2
- return
0
if same,<0
ifs1 < s2
,>0
ifs1 > s2
- compare
Dynamically allocating space for strings and putting them in an array:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void addstring(char **stringarray, char *newstring, int * numptr)
{ printf("allocating %lu bytes for %s\n",strlen(newstring)+1,newstring);
stringarray[*numptr] = malloc(strlen(newstring)+1);
strcpy(stringarray[(*numptr)++],newstring);
}
int main()
{
int numstrings = 0;
char *sarray[100];
addstring(sarray, "hi", &numstrings);
addstring(sarray, "ho", &numstrings);
addstring(sarray, "wee", &numstrings);
for (int i=0; i < numstrings; i++) {
printf("%s\n",sarray[i]);
// must also free the strings to prevent memory leaks
free(sarray[i]);
}
}
See also the Pointers & Dynamic Memory Allocation notes resource.