Search code examples
cargv

How to index through argv[1] in C?


If I have:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int length = strlen(argv[1]);

and argv[1] one is just a word, for example, "hello", how can I index through it backwards and print out letter by letter?

I tried using strrev, but apparently this isn't in linux and rather than include the function I'd rather just for loop through argv[1] backwards.

I tried:

int i;  
for (i = length; i == 0; i--){

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

but I knew this would be wrong before I even executed it.


Solution

  • how can I index through it backwards and print out letter by letter

    int i;  
    for (i = strlen( argv[1] ) - 1 ; i >= 0; i--){
        printf("%c", argv[1][i]);
    }
    

    Also, of course you need to #include <string.h> for string-related functions like strlen.