使用strcpy在数组中存储char


char strr[10];
strcpy(strr, argv[1]);

这适用于存储整个参数,但我如何使用相同的技术如果我想存储第一个参数中的某个字符。

strcpy(strr, argv[1][1]);

当然,这不会起作用,因为它是一个字符,所以我想知道我还能怎么做

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

不能使用strcpy在数组中存储字符。strcpy用于字符串,而不是字符。

但你可以用另一种方式。

很简单:

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

现在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.
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
}

最新更新