0

So I try to take a user input of unknown max length from the command line. The program to be able to do something like that needs to take a dynamic input of a string (char array maybe?). The outcome should be something like

./a.out st1 your str is ...

the only code I was able to come up with is the following

int main (int argc, char* argv[]){
    ...
    char str1[];
    str1 = argv[1];
    printf("your...);
    ...
}
Code Plus
  • 150
  • 1
  • 12
Angelo
  • 15
  • 4

2 Answers2

2

This declaration of a block scope array with an empty number of elements:

char str1[];

is incorrect. Moreover arrays do not have the assignment operator:

str1 = argv[1];

You could declare a pointer:

char *str1;
str1 = argv[1];
printf("your...);
halfer
  • 19,824
  • 17
  • 99
  • 186
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

C will terminate argv with a null pointer, and argv is modifiable, so it's actually very easy to implement shift like in bash scripts. Your basis could look like the following.

#include <stdio.h>

int main(int argc, char *argv[]) {
    char *arg;
    if(!argc || !argv[0]) return 0; /* Defensive */
    while(arg = *(++argv))
        printf("do something with %s\n", arg);
    return 0;
}
Neil
  • 1,767
  • 2
  • 16
  • 22
  • 1
    Or you could write a readable loop instead of obscure pointer arithmetic: `for(int i=0; i – Lundin Dec 20 '21 at 08:47
  • True; not just about style, the way you propose is good if you want the index at which the argument occurs. – Neil Dec 20 '21 at 21:51