strcpy((*pointeur).caractere, x);
I use strcpy
to copy the value of x
to (*pointeur).caractere
and I define the struct
typedef struct cle{
char caractere;
int compteur;
struct cle *suivant;
}cle_t;
and declare the pointer
cle_t *pointeur;
but the compiler told me that
"invalid conversion from 'char' to 'char*'"
and
"initializing argument 1 of `char* strcpy(char*, const char*)' "
I can't understand what goes wrong...
Thank you all guys~
Salut !
caractere
is a character, and strcpy
works with strings. There are two solutions, according to what you want to do (with your identifiers, I guess you are rather in the fist case).
- If
x
is a char
, use pointeur->caractere = x
(no need to strcpy
to copy characters).
- If
x
is a char*
or a char[]
, declare caractere
as a string with a sufficient length (ie with an array of char
or a pointer to char
dynamically allocated), and then you can call strcpy
.
strcpy((*pointeur).caractere, x);
This will work fine but caractere
should be a char *
or char[]
here is the declaration of strcpy()
char *strcpy(char *dest, const char *src);
Also note that if you are creating caractere
as a char*
then make sure to allocate memory for this other wise using strcpy()
will give undefined behaviour
or may lead to seg fault
One more thing : If you are making a pointer to struct
then you can directly use ->
operator to access the data members
1- syntax:
You have a pointer to a struct and then access its fields: this case is so common that C provides ''syntactic honey'' (du ''miel syntaxique''; en fait l'expression réelle est ''syntactic sugar'', je plaisante):
(p_struct*).field
// -->
p_struct->field
In your case:
strcpy((*pointeur).caractere, x);
// -->
strcpy(pointeur->caractere);
Use this form not only because it's nicer, but because everyone uses the arrow, so the meaning is more obvious.
2- strcpy
copies strings, not characters. Strings are character arrays, with a 0
at the end, or pointers to them. So, if you want to use strcpy, you need either to replace the field caractere
with a field chaine
holding a string, or make a string on the fly from caractere
before passing it to strcpy
. But if you only want to copy the char, just copy it with =
.
3- Beware of the misleading term "character". A C char
actually is just a byte (moreover, either signed or not depending on your platform). For universal text, that is anything but ASCII, an actual character (in the evryday, linguistic, or programming sense) may be represented with one or more codes, each taking one or more bytes (C char
s). (See UCS & Unicode on wikipedia.)