I receive this error:
array.cpp: In function 'void strcat2(char*, const char*)': array.cpp:74: error: invalid conversion from 'char' to 'char*' array.cpp:74: error: initializing argument 1 of 'void strcpy2(char*, const char*)' array.cpp:74: error: invalid conversion from 'char' to 'const char*' array.cpp:74: error: initializing argument 2 of 'void strcpy2(char*, const char*)'
When trying to run this code:
//Concatenates two arrays of characters using pointers
void strcat2(char* t, const char* s)
{
unsigned int i;
for (i = 0; *t; i++);
strcpy2(*(t + i), *s);
}
Here is the strcpy2 function it calls:
//Copies the information from one array of characters to another using pointers
void strcpy2(char* t, const char* s)
{
for ( ; *t++ = *s++;);
}
It says invalid conversion from char to char*, but where am I trying to convert from char to char*? It seems to me that everything in the code is char*. What am I missing?
I've looked over this code many times and can't seem to find what is wrong. I'm relatively new to pointers, go easy! Thank you very much for any help!
*(t + i)
t
is of type char *
.
so t + i
means char * + i
which means "add the value of i to the pointer to make a new pointer". *(t + i)
then dereferences that new pointer, the type of that dereferenced expression will be char
. So yes, the compiler is correct. You're trying to pass a char
into a function that expects a pointer-to-char
.
You simply want
strcpy2(t + i, s);
note: You were also dereferencing s
, which would cause the same compile error.
The expression *(t + i)
in strcpy2(*(t + i), *s);
is a char type because the *
dereferences the pointer.
Change these statements
for (i = 0; *t; i++);
strcpy2(*(t + i), *s);
to
for (i = 0; *(t + i ); i++);
strcpy2( t + i, s);
Also it would be better to declare the functions as having return type char *
. For example
char * strcat2(char* t, const char* s);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.