Sami
Sami

Reputation: 195

How to parse a string that's in one index of an array?

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?

Upvotes: 0

Views: 105

Answers (2)

lwzhuo
lwzhuo

Reputation: 324

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.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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.

Upvotes: 1

Related Questions