如何添加两个字符串?
How to add two strings?
#include <stdio.h>
int main ()
{
char a[] = "My name is";
char b[] = "kamran";
printf("%s %s", a+b);
return(0);
}
我试图添加两个字符串,但出现 "Invalid operands to binary"
错误
您可以像这样将 b
连接到 a
:
char a[18] = "My name is "; // a needs to be big enough
char b[] = "kamran";
strcat(a, b);
printf("%s", a);
要使用 strcat()
,您需要包含 string.h
。
在这个表达式中
a+b
数组指示符被隐式转换为指向字符串第一个字符的指针。所以实际上你试图添加两个 char *
.
类型的指针
来自 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array object
has register storage class, the behavior is undefined.
但是 operator +
没有为 C 和 C++ 中的指针定义。
如果您确实想要添加两个字符串,那么操作的结果将是包含前两个字符串的第三个字符串。
有两种方法。您要么声明第三个字符数组,其大小足以包含前两个字符串。或者您需要为结果字符串动态分配内存。
例如
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main( void )
{
char a[] = "My name is";
char b[] = "kamran";
char c[sizeof( a ) + sizeof( b )];
strcpy( c, a );
strcat( c, " " );
strcat( c, b );
puts( c );
char *d = malloc( sizeof( a ) + sizeof( b ) );
if ( d )
{
strcpy( d, a );
strcat( d, " " );
strcat( d, b );
puts( d );
}
free( d );
}
程序输出为
My name is kamran
My name is kamran
#include <stdio.h>
int main ()
{
char a[] = "My name is";
char b[] = "kamran";
printf("%s %s", a+b);
return(0);
}
我试图添加两个字符串,但出现 "Invalid operands to binary"
错误您可以像这样将 b
连接到 a
:
char a[18] = "My name is "; // a needs to be big enough
char b[] = "kamran";
strcat(a, b);
printf("%s", a);
要使用 strcat()
,您需要包含 string.h
。
在这个表达式中
a+b
数组指示符被隐式转换为指向字符串第一个字符的指针。所以实际上你试图添加两个 char *
.
来自 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
但是 operator +
没有为 C 和 C++ 中的指针定义。
如果您确实想要添加两个字符串,那么操作的结果将是包含前两个字符串的第三个字符串。
有两种方法。您要么声明第三个字符数组,其大小足以包含前两个字符串。或者您需要为结果字符串动态分配内存。
例如
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main( void )
{
char a[] = "My name is";
char b[] = "kamran";
char c[sizeof( a ) + sizeof( b )];
strcpy( c, a );
strcat( c, " " );
strcat( c, b );
puts( c );
char *d = malloc( sizeof( a ) + sizeof( b ) );
if ( d )
{
strcpy( d, a );
strcat( d, " " );
strcat( d, b );
puts( d );
}
free( d );
}
程序输出为
My name is kamran
My name is kamran