0

I'm writing a program in C that receives two strings as input from the user on the command line. I know that when you use

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

it creates a pointer to the array that stores both arguments as argv[1] and argv[2]. Say the user inputs "hello" on the command line, and I want to access the individual characters in "hello", how can I do so if argv[1] gives me the whole string rather than individual characters?

6
  • argv[x] (for any valid x) is a string. You access individual elements of that like you do for any other string. You have encountered array of arrays before? Treat argv like an array of arrays. Commented Feb 14, 2019 at 5:30
  • @SaniJr: argv here is a 2 dimensional array. so in your example argv[1][0] is 'h', argv[1][1] is 'e' and so on. so you can run a for loop to the length of argv[1] and get each entry with argv[1][i]. Commented Feb 14, 2019 at 5:32
  • @Deepak Thanks a lot that's what I was looking for. Didn't think of it as a 2D array. Commented Feb 14, 2019 at 5:41
  • 3
    argv is not a 2D array. argv is a pointer, a pointer to a char *. Commented Feb 14, 2019 at 6:05
  • Sorry, it is not a 2D array. It is a pointer to a pointer. where each row can string can have its own size of character. it will not have the fixed dimension. Commented Feb 14, 2019 at 6:39

2 Answers 2

1

TL;DR- When in doubt, check the data type.

The type for argv is char * [], which decays to char **. Thus, argv[n] is of type char *.

You can index into argv[n], like argv[n][m] to get the char elements.

Sign up to request clarification or add additional context in comments.

Comments

0

You can treat char *argv[] to a string array.

As the char * is a pointer which point to char array(also can treat as a string).

So the argv[0],argv[1].... are the char* data type, the argv[0][0] is char data type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.