我正在学习 C,但遇到了困难。基本上我声明了 2 个数组,我想使用指针将一个数组的所有 char 值复制到另一个数组中。我利用了数组名称是指向其第一个元素的指针这一事实。有人可以看一下并提供帮助吗?谢谢。
#include<stdio.h>
#include<string.h>
char *mystrcopy(char*p, char*q); //function prototype
int main(void)
{
char s1[20] = "Hello\n";
char s2[20] = "Bye\n";
puts(s1); //print Hello
mystrcopy(s1, s2); //call function using pointers s1 and s2
puts(s1); //I want this to print Bye after function has run
system("pause"); //"press any key to continue...."
return 0;
}
char *mystrcopy(char*s1, char*s2)
{
int i;
for (i = 0; s1 + i; i++) //for loop continues as long as s1+1 not 0
s1 + i = s2 + i; //error says s1 is not a modifiable lvalue
return s1; //I know this could be a void function but I choose not to
}
我认为这很好,因为 (s1 + i) 是一个指向数组 s1 中第 i 个元素的指针,并将其替换为 s2 中的第 i 个元素。
我尝试使用
*(s1+i) = *(s2+i)
相反,将 s2 的地址复制到 s1 中,但我得到了同样的错误。
编辑:
上面的for循环代码确实有效
*(s1+i) = *(s2+i)
我认为这不起作用,因为循环一直在进行。不过,感谢大家回答我关于可修改 l 值的问题。
最佳答案
类似这样的事情将帮助您开始。请注意,我们必须在拷贝中取消引用 char*。这假设固定长度字符串,因此不需要使用 std 库中的 malloc 或 strlen 函数。并不理想,但您可以使用它来开始。
#include<stdio.h>
#include<string.h>
char *mystrcopy(char* p, char* q); //function prototype
#define LENGTH 20
int main(void){
char s1[LENGTH] = "Hello\n";
char s2[LENGTH] = "Bye\n";
puts(s1); //print Hello
mystrcopy(s1, s2);
puts(s1); //I want this to print Bye after function has run
// system("pause"); //"press any key to continue...."
return 0;
}
char *mystrcopy(char* s1, char* s2)
{
int i;
for (i = 0; i < LENGTH; i++, ++s1, ++s2) //for loop continues as long as s1+1 not 0
*s1 = *s2; //error says s1 is not a modifiable lvalue
return s1; //I know this could be a void function but I choose not to
}
关于c++ - C:尝试将指针值复制到另一个指针中,出现可修改左值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945378/