Search code examples
citeration

How to iterate over a string in C?


Right now I'm trying this:

#include <stdio.h>

int main(int argc, char *argv[]) {

    if (argc != 3) {

        printf("Usage: %s %s sourcecode input", argv[0], argv[1]);
    }
    else {
        char source[] = "This is an example.";
        int i;

        for (i = 0; i < sizeof(source); i++) {

            printf("%c", source[i]);
        }
    }

    getchar();

    return 0;
}

This does also NOT work:

char *source = "This is an example.";
int i;

for (i = 0; i < strlen(source); i++){

    printf("%c", source[i]);
}

I get the error

Unhandled exception at 0x5bf714cf (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation while reading at position 0x00000054.

(loosely translated from german)

So what's wrong with my code?


Solution

  • 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 which is why for strings it's best to always use strlen.

    Also note what others have said about changing printf to use %c, and, 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++) {