Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用strcpy在数组中存储字符_C - Fatal编程技术网

用strcpy在数组中存储字符

用strcpy在数组中存储字符,c,C,这可以很好地存储整个参数,但是如何使用相同的技术呢 如果我想存储第一个参数中的某个字符 char strr[10]; strcpy(strr, argv[1]); 这当然不行,因为它是一个字符,所以我想知道我还能怎么做 编辑: 我只使用了char-strr[10];作为字符数组的示例。请不要注意它的大小。您不能使用strcpy在数组中存储字符strcpy用于字符串,而不是字符 但你可以用另一种方式 很简单: strcpy(strr, argv[1][1]); 现在sttr是一个只包含一个字符

这可以很好地存储整个参数,但是如何使用相同的技术呢 如果我想存储第一个参数中的某个字符

char strr[10];
strcpy(strr, argv[1]);
这当然不行,因为它是一个字符,所以我想知道我还能怎么做

编辑:
我只使用了char-strr[10];作为字符数组的示例。请不要注意它的大小。

您不能使用strcpy在数组中存储字符<代码>strcpy用于字符串,而不是字符

但你可以用另一种方式

很简单:

strcpy(strr, argv[1][1]);
现在
sttr
是一个只包含一个字符的字符串(以及强制的字符串终止)

除此代码外,您还需要确保
argv[1]
有效,并且
argv[1][1]
有效

比如:

char strr[2] = { 0 };   // Make strr a string that can hold 1 char and a 
                        // string termination. Initialize to zero.

strr[0] =  argv[1][1];  // Copy the second char of the string pointed to by 
                        // argv[1] to the first char of strr

你不能那样做。您应该使用类似于
strr[0]=argv[1][1]。这看起来像。
strcpy
复制字符串。要复制单个字符,只需分配给另一个字符变量。
argv[1][1]
是一个
char
。或者您可能需要
strncpy(strr,&argv[1][1],1)
(这似乎更难理解)如果
argv[1]
超过9个字符会发生什么?
char strr[2] = { 0 };   // Make strr a string that can hold 1 char and a 
                        // string termination. Initialize to zero.

if (argc > 1 && strlen(argv[1]) > 1)
{
    strr[0] =  argv[1][1];  // Copy the second char of the string pointed to by 
                            // argv[1] to the first char of strr
}