0

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
Guy Levy
  • 1,550
  • 2
  • 15
  • 26
Barak
  • 43
  • 7

3 Answers3

1

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*

IrAM
  • 1,720
  • 5
  • 18
  • well yes string type char how to i store in a variable then ? – Barak Dec 11 '20 at 17:45
  • Is there any other way without using cmd arg ? I need to work with argv because I have setup arguments in tab bunch of strings, I need the use argv and pass into uppercase one by one! – Barak Dec 11 '20 at 18:08
1

you should use a char pointer instead of a char array:

char *s = argv[1];

See this for reference : What is the difference between char array and char pointer in C?

chlotte
  • 11
  • 5
1

argv[1] is not a char array. It's a pointer to the char array. So you need to assign char s like this:

char *s = argv[1];

Also, you can use malloc with memcpy from stdlib.h and strlen from string.h to copy argv[1] to s (recommended if you want to do some modifications with s later):

size_t len = strlen(argv[1]))+1; // 1 for NULL byte
char *s = malloc(len);
memcpy(s, argv[1], len);

The advantage of second approach is ability to reallocate memory later.

Vlad Havriuk
  • 1,291
  • 17
  • 29