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++) {

Leave a Comment