简体   繁体   English

C-将命令行参数存储为Char数组

[英]C - Store Command Line Argument as an Array of Char

If I have these two command line arguments, is there a way that I can take the second command line argument which is a single word containing 26 characters, separate all the letters and put them into a new array of characters? 如果我有这两个命令行参数,是否可以采用第二个命令行参数,它是一个包含26个字符的单词,将所有字母分开并将它们放入一个新的字符数组中?

./substitution qwertyuiopasdfghjklzxcvbnm

I tried using this syntax but I'm not sure if it is valid? 我尝试使用此语法,但不确定是否有效?

char mapping[] = argv[1];

I thought that this statement would create a new array of characters called mapping, and assign it to a string since I'm assuming argv[1] is a string. 我认为该语句将创建一个称为映射的新字符数组,并将其分配给字符串,因为我假设argv[1]是字符串。 Then each index would have the respective characters as per the command line argument: 然后,每个索引将根据命令行参数具有各自的字符:

mapping[0] = 'q'
mapping[1] = 'w'
...

Any tips would be appreciated! 任何提示将不胜感激! :) :)

you cant assign value to an array like that. 你不能像这样给数组赋值。 but instead you can use pointers. 但是您可以使用指针。 argv is an array of pointers to null terminated strings. argv是一个以null结尾的字符串的指针数组。 which means they has the character '\\0' with ASCII value of zero at the end. 这意味着它们的字符“ \\ 0”结尾处的ASCII值为零。

char *mapping = argv[1];

now mapping points to the first argument. 现在mapping指向第一个参数。 and if you need a copy of the first arg you should allocate enough memory for the string with malloc ( stdlib.h ) function and then copy it to that block of memory with strcpy ( string.h ). 如果需要第一个arg的副本,则应该使用mallocstdlib.h )函数为字符串分配足够的内存,然后使用strcpystring.h )将其复制到该内存块中。

char *mapping = malloc(strlen(argv[1]) + 1); //strlen returns the size of the string not including the null character at the end.
strcpy(mapping,argv[1]);
...
free(mapping);//then you will have to free the allocated space when you are done with it.

now mapping is copy of argv[1] and modifying it wont affect argc[1] . 现在mappingargv[1]副本,对其进行修改不会影响argc[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM