Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c - Why can´t we assign a new string to an char array, but to a pointer?

i was trying to reassign a string to a pre-initialized array a[], and all i could get was an error

main()
{
    char a[] = "Sunstroke";
    char *b = "Coldwave";

    a = "Coldwave";
    b = "Sunstroke";
    printf("
 %s %s",a,b);
}

[Error]: incompatible types when assigning to type 'char[10]' from type 'char *'.. i searched for this but was unable to find any reason.. i also tried to re-assign it by redeclaration like

char a[] = "Sunstroke";

but it didnt worked...

but in case of a pointer it was possible as in above program..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To understand what's going on here, two language rules are important:

  • Arrays are not assignable.
  • An array can be converted to a pointer to its first element.

It's also important to understand what a string literal like "Sunstroke" is. It's a static array of constant characters, large enough to hold all the characters of a string with a terminator at the end. So in this case, it's a const char[10] array, containing the nine characters followed by the zero-valued terminator. Being static, the array is stored somewhere in memory for the lifetime of the program.

char a[] = "Sunstroke";

This creates a local array, and initialises it by copying the characters from the string literal.

char *b = "Coldwave";

This creates a pointer, and initialises it to point to the literal itself. Note that this is dangerous: the literal is const, but the pointer isn't, so you can write code that attempts to modify the literal, giving undefined behaviour. This conversion is deprecated (certainly in C++, I'm not sure about C), so the compiler should give you a warning. You have enabled all the compiler warnings you can, haven't you?

a = "Coldwave";

This attempts to reassign the array, but fails because arrays aren't assignable. There's no particularly good reason why they aren't; that's just the way the languages evolved.

b = "Sunstroke";

This reassigns the pointer to point to a different literal. That's fine (apart from the lack of const noted above).

If you need to manipulate strings, then:

  • in C you'll need to carefully create arrays large enough for your needs, and use the library functions in <string.h> (or your own handcrafted code) to manipulate the characters in those arrays;
  • in C++, use the std::string class to handle memory management, assignment, etc. for you.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...