How to iterate over a string in C?
You want:
for (i = 0; i < strlen(source); i++) {
sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:
char source[] = "This is an example.";
but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:
int len = strlen(source);
for (i = 0; i < len; i++) {
or rewrite the loop:
for (i = 0; source[i] != 0; i++) {
One common idiom is:
char* c = source;
while (*c) putchar(*c++);
A few notes:
- In C, strings are null-terminated. You iterate while the read character is not the null character.
*c++
incrementsc
and returns the dereferenced old value ofc
.printf("%s")
prints a null-terminated string, not a char. This is the cause of your access violation.
An optimized approach:
for (char character = *string; character != '\0'; character = *++string)
{
putchar(character); // Do something with character.
}
Most C strings are null-terminated, meaning that as soon as the character becomes a '\0'
the loop should stop. The *++string
is moving the pointer one byte, then dereferencing it, and the loop repeats.
The reason why this is more efficient than strlen()
is because strlen already loops through the string to find the length, so you would effectively be looping twice (one more time than needed) with strlen()
.
Rather than use strlen as suggested above, you can just check for the NULL character:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char *const pszSource = "This is an example.";
const char *pszChar = pszSource;
while (pszChar != NULL && *pszChar != '\0')
{
printf("%s", *pszChar);
++pszChar;
}
getchar();
return 0;
}