[英]C: String Concatenation via Pointers
I am learning C.. coming from a C# background I find most of it very easy to transition over to.. pointers however are proving quite troublesome.. I have created a small test app (see below) for concatenating 2 strings via pointers. 我正在学习C ..来自C#背景,我发现其中的大部分内容都非常容易过渡到..指针,但是事实证明这很麻烦。.我创建了一个小型测试应用程序(请参见下文),用于通过指针连接2个字符串。 I am getting this error:
我收到此错误:
error: invalid type argument of unary '*' (have 'int')
How do I fix this? 我该如何解决?
void concatTest();
int main()
{
concatTest();
system("PAUSE");
return 0;
}
void concatTest()
{
char string1[20], string2[20], string3[40];
char *ptr1, *ptr2, *ptr3;
ptr1 = &string1[0];
ptr2 = &string2[0];
ptr3 = &string3[0];
int i;
printf("You need to enter 2 strings.. each of which is no more than 20 chars in length: \n");
printf("Enter string #1: \n");
scanf("%s", string1);
printf("Enter string #2: \n");
scanf("%s", string2);
int len1 = strlen(string1);
int len2 = strlen(string2);
for (i = 0; i < len1; i++)
{
*ptr3[i] = *ptr1[i];
}
for (i = len1; i < len1 + len2; i++)
{
*ptr3[i] = *ptr2[i];
}
//TODO: show concatenated string on console
}
ptr1[i]
has already dereferenced the array. ptr1[i]
已经取消引用数组。 There is no need to use *
as well. 也不需要使用
*
。
[ However, even if you fix that, your code is still broken; [ 但是,即使您修复了该错误,您的代码仍然会损坏; you haven't taken null-terminators into account.
您没有考虑空终止符。 ]
]
the name of array as a point
ptr1 = string1; ptr1 point at the array string1,so ptr1[i] is just like string1[i]
ptr1 = string1;
ptr2 = string2;
ptr3 = string3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.