Reputation: 13
I have set a structure type:
typedef struct {
char *snt[MAX_LINE_LENGTH];
} sentence;
And this line is getting a cast specifies array type
error:
sentence copySentence(sentence *source) {
sentence nw;
nw.snt = (char *[])source->snt; //Here is the error
return nw;
}
What is the best fix for this code line and what is the problem?
Upvotes: 0
Views: 1898
Reputation: 16117
Both nw.snt
and source->snt
are arrays of pointer. To "deep copy" the whole array, you may want to use memmove(nw.snt, source->snt, MAX_LINE_LENGTH * sizeof (char *));
.
Also, people usually prefer passing a pointer to a struct than pass that struct directly to reduce the cost of argument passing. In this case, you can
sentence *copySentence(sentence *source) {
sentence *nw;
nw = malloc(sizeof (struct sentence));
memmove(nw.snt, source->snt, MAX_LINE_LENGTH * sizeof (char *));
return nw;
}
Upvotes: 1
Reputation: 25286
You are declaring snt
as an array of pointers to charactes. You probably mean it t be an array of charactes, or a pointer to an array of characters:
char snt[MAX_LINE_LENGTH]; // array of characters to hold your sentence
char *snt; // pointer to array of characters
When you assign an element to a compatible element, there is no need for a cast and casting is here considered harmful because you prevent the compiler from giving you warnings. Note that you do not copy the characters, you only make two structs point to the same sentence.
I leave fixing this to you, as an excercise.
Upvotes: 0