Reputation: 4163
What I am trying to do is add a command line argument into an array as indvidual characters.
So when the user runs the program ./program bacon
"bacon" is stored in an array as
array k[]= {'b', 'a', 'c', 'o', 'n'};
I hope I explained it well enough I am new to programming.
Upvotes: 1
Views: 2513
Reputation: 14205
So, I understand you're new to programming, but surely this looks familiar, no?
int main (int argc, char **argv) {
// ...
}
char **argv
is a pointer to a char pointer, but for your purposes, you can consider it to be the equivalent of char *argv[]
. The difference is subtle, but worth noting, since this caveat is vital to understanding the way strings work in C. char *argv[]
is explicitly typed as an array of char pointers, while char **argv
could be an array but you wouldn't know until you try to access it as such. Given that it's your main function, it's safe to assume this will always be instantiated appropriately.
Anyway, moving past the tangent, we have an array of null-terminated strings in char **argv
in our main function. From your question, I can see a simple path we should follow. I will assume that only one argument is expected (you should otherwise be capable of implementing cases which deal with different circumstances).
argv[1]
) passed to our program.argv[1]
.In our main
function, we store the length of argv[1]
to n
, and declare our array of size n
. We then iterate through the first string, character-by-character, and store each character into the next open slot of our array. At the end, we repeat our loop and print out each item of our array so we can verify it works.
int main (int argc, char *argv[]) {
int n = strlen(argv[1]);
char arr[n];
int i;
for (i = 0; i < n; i++)
arr[i] = argv[1][i];
for (i = 0; i < n; i++)
printf("%c ", arr[i]);
printf("\n");
}
Hope this helps. Cheers.
Upvotes: 0
Reputation: 24905
Effectively, "bacon" will be passed to you through argv1 which is a char *
and a null terminated string. Now your array which you want to create should also be a char array.
Logically you should just be copying the input (argv1) into the new array.
You can use string manipulation functions like strcpy or strncpy
Note: I am not directly adding the code in this solution as it will be better for you to try it yourself.
Upvotes: 1
Reputation: 1554
Use arguments passed to main. You will already get an array argv[1] which does this for you. I think it's best you read some articles like this one to get started - http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html
Upvotes: 0