Reputation: 11
I am working on creating a linked list in c++, and I can't figure out how to pass an array as an argument in the constructor, or if thats even legal syntax.
This is the error I get:
CheckTextFile.cpp: In constructor ‘Node::Node(char*, int)’:
CheckTextFile.cpp:19: error: incompatible types in assignment of ‘char*’ to ‘char [0u]’
CheckTextFile.cpp: In constructor ‘Node::Node(char*, int, Node*)’:
CheckTextFile.cpp:24: error: incompatible types in assignment of ‘char*’ to ‘char [0u]’
Here is my code:
class Node{
public:
int length;
char data[];
Node * next;
Node(char x[], int y){
data = x;
length = y;
next = NULL;
}
Node(char x[], int y, Node * z){
data = x;
length = y;
next = z;
}
};
Upvotes: 1
Views: 1656
Reputation: 11787
class Node{
public:
int length;
char *ptr_data; //pointer
Node * next;
Node(char *x, int y){
ptr_data = x; //pointer assignment
length = y;
next = NULL;
}
Node(char *x, int y, Node * z){
ptr_data = x; //pointer assignment
length = y;
next = z;
}
};
Upvotes: 0
Reputation: 206636
You are passing an pointer to the first element of the array, and actually that is correct.
The compiler is complaining about assignment inside the constructor:
data = x;
You cannot assign arrays as such, not like objects, you will have to copy each element from the source array to the target array.
Either using a looping construct or using std::copy
.
A trivial way(efficient would be to use std::copy
) of doing so:
Node(char x[], int y)
{
for(int i = 0;i<y; ++i)
{
data[i] = x[i];
}
length = y;
next = 0;
}
Or Simply
std::copy(x,x+y,data);
And it will compile cleanly.
On a side note, you are much better off using std::string
rather than using char arrays.
Upvotes: 1
Reputation: 733
First of all, in C++, you can't have an array of unspecified size. Also, you can use a pointer instead of an array or std:string
.
Upvotes: 0
Reputation: 994599
Your argument passing is fine. However, your:
char data[];
declares an array with no size, so it's not surprising that the compiler refuses to generate code to put anything in there. Perhaps try:
std::string data;
This is assuming that your x[]
represents a NUL-terminated C string.
After you do that, learn about the member initialisation syntax for constructors.
Upvotes: 3