Search code examples
cfunctionargumentsfunc

C: How to implement argv into variable and implement for loop?


I am working on creating an uppercase function for practice. I want to implement argc and argv arguments with for loop for checking each input values in to my code but When use argv like that it wont work:

char s[] = argv[0];

But this is working:

uppercase(argv[1]);

How can I implement my arguments into variable with for loop?

Here is my code;

Main.c:

#include <stdio.h>
#include <stdlib.h>

#include "upperc.h"


int main(int argc, char *argv[])
{
    char s[] = argv[1]; // This is giving me a error.

    printf("%s \n", uppercase(argv[1])); // This is working

    return 0;
}

upper.c:

/*
Parsing the string, then making the letters to uppercase.
*/

#include <stdio.h>
#include "upperc.h"

#define MAGIC_NUMBER 32 //6th bit ability of letter chars

char * uppercase(char *s) {
    for(char *p = s; *p; ++p) {
        if ('a' <= *p && *p <= 'z')
            *p = *p - MAGIC_NUMBER;
    }

    return s;
}

upper.h:

#ifndef UPPERC_H_INCLUDED
#define UPPERC_H_INCLUDED

char * uppercase(char *s);

#endif // UPPERC_H_INCLUDED

Solution

  • case 1

    char s[] = argv[0]; here s is an array and argv[0] is a pointer or address.

    You cannot store some pointer in an array

    Instead use char *cmd_arg = argv[0];

    If you want to read set of command line arguments use loops to iterate over set of command line inputs

    //since argv[0] indicates program name , starting `a` from 1 instead of 0
    for(int a = 1; a < argc; a++)
        uppercase(argv[a]);   
    

    case 2

    uppercase(argv(1)); i think you mean by uppercase(argv[1]);

    That is fine because uppercase is accepting a pointer char*