Daniel
Daniel

Reputation: 23

Dynamic Structure in C++

struct testing
{
    char lastname[20];        
};

testing *pt = new testing;            
pt->lastname = "McLove";

and I got

56 C:\Users\Daniel\Documents\Untitled2.cpp incompatible types in assignment of 'const char[7]' to 'char[20]'

Why ?

Thanks in advance.

Upvotes: 2

Views: 3405

Answers (4)

Seth Carnegie
Seth Carnegie

Reputation: 75130

Because compile time arrays are constant. In your struct testing, you have an array of 20 chars, and you're trying to assign a pointer ("McLove", a compile time string, e.g., a const char*) to an array (a char[]), which won't work.

To copy the data "McLove" into the array, you need to use strncpy:

strncpy(pt->lastname, "McLove", 20); // 20 is the size of the array, change it when your array size changes, or better yet, use a constant for both

Or better yet, use std::string:

struct testing {
    string lastname;
};

testing* pt = new testing;

pt->lastname = "McLove";

And now that will work, because std::string has an operator= that works with const char*.

As a side note, don't needlessly allocate objects on the free store (using new); allocate them on the stack:

testing pt; // not: testing* pt = new testing;

testing.lastname = "McLove"; // with std::string

Upvotes: 3

Praetorian
Praetorian

Reputation: 109119

Because string literals in C++ have the type const char[N] where N is the length of the literal, including the NULL character. So you're trying to assign a const char[7] to a array of type char[20], exactly what the compiler told you. Since arrays are not assignable this is invalid.

Use strcpy instead

strcpy( p-lastname, "McLove" );

Of course, you should also check if the destination is large enough to hold the source, or use some variant of strcpy that does this.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

The type of a string literal is pointer to const char. You can use that to initialize an array of char, but you can't assign to an array of char (from that or anything else).

Since you're apparently doing C++, you probably want:

struct testing { 
     std::string lastname;
};

testing pt;
pt.lastname = "McLove";

Allocating an object like testing dynamically is fairly unusual.

Upvotes: 2

Chris Eberle
Chris Eberle

Reputation: 48775

You can't assign one array to another. You're going to need to use strcpy (or better, strncpy).

Upvotes: 1

Related Questions