c++ - C:尝试将指针值复制到另一个指针中,出现可修改左值错误

标签 c++ c arrays

我正在学习 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/

相关文章:

c - fscanf 覆盖内存中的下一个字节 (C)

c++ - 越界访问数组是否被视为违反类型安全或违反内存安全?

javascript - 在日期数组中,如何查找给定日期(javascript)中最接近的前一个日期?

c++ - 大多数顺序值指向同一对象的查找表?

android - Cocos2d-x 3.13.1 : error with cocos run (Android)

c++ - 是否有接受预填充和预分配缓冲区的随机访问容器类型?

python - 使用 Python 且不使用 NumPy 的 2D 数组元素计算

c++ - 如何忽略空格和标点符号?

c++ - 如何将光流场(float)映射到像素数据(char)以进行图像变形?

c - 从函数返回的 char* 数组打印不正确的值(可能是内存管理)