Copy string in C

Shervan360 1,661 Reputation points
2020-09-12T08:33:10.32+00:00

Hello,

Could you please explain why we cannot assign a string to another, whereas, we can assign a char pointer to another char pointer?

Thanks

#include<stdio.h>

int main()
{
    char str1[] = "Hello";
    char str2[10];

    char* s = "Good Morning";
    char* q;

    str2 = str1; //error, Why does it NOT work?
    q = s; //works, Why does it work?

    return 0;
}
Developer technologies C++
0 comments No comments
{count} votes

Accepted answer
  1. WayneAKing 4,931 Reputation points
    2020-09-12T12:37:20.737+00:00

    A C string is a nul-terminated character array.

    The C language does not allow assigning the contents of an array to another
    array. As noted by Barry, you must copy the individual characters one by one
    from the source array to the destination array. e.g. -

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char str1[] = "Hello";
        char str2[10] = {0};
    
        for (int x = 0; x < strlen(str1); ++x)
        {
            str2[x] = str1[x];
        }
    
        printf("%s\n", str2);
    
        return 0;
    }
    

    To make this common task easier there are standard library functions provided
    which will perform this operation. e.g. - memcpy(), etc.

    memcpy(str2, str1, 6);

    When the array contains a nul-terminated string of characters you can use
    strcpy(), etc.

    strcpy(str2, str1);

    Caveat: Some of the above functions are considered unsafe as they do not guard
    against buffer overruns of the source and destination arrays. There are safer
    versions provided by the compiler.

    Note that if and when you start learning C++ you will find that there you can
    assign a C++ std::string object to another object of the same type. However,
    even in C++ the same rules apply when working with C strings, "raw" character
    arrays, etc.

    • Wayne
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Barry Schwarz 3,746 Reputation points
    2020-09-12T08:44:22.077+00:00

    str2 is an array. It cannot appear on the left side of an assignment. You will need to use something like strcpy.

    q is a pointer. It is perfectly legal to copy one pointer to another.

    2 people found this answer helpful.
    0 comments No comments

  2. RLWA32 49,536 Reputation points
    2020-09-12T09:06:12.297+00:00

    Hmm, this looks familiar. Another "Expression must be a modifiable lvalue" problem.

    Arrays versus Pointers Redux.

    I suggest you re-read the references provided in the answer you accepted to your earlier question -- expression-must-be-a-modifiable-lvalue.html

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.