I have a *char pointer and a char array. How can I put the value of the pointer in the char array? I've tried
uint8_t i;
char a[10];
char *b = "abcdefghi";
for(i = 0; i < 9; i++)
{
a[i] = b[i];
}
printf("%s", a);
But this doesn't work.
The size of a
is 10
, so is the length of b
(including the null terminator). Change
for(i = 0; i < 9; i++)
to
for(i = 0; i < 10; i++)
What you are doing is right.
Juts change i<10
in your for loop.
There are 10 elements in your char array and the array index is from 0-9
.
yet another variant:
#include <stdio.h>
int main(void)
{
char a[10];
char *c = a;
char *b = "abcdefghi";
for(; *c = *b; ++c, ++b);
printf("%s", a);
return 0;
}
but strcpy()
will work faster in any case, since it is often written in assembly language for a specific architecture
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.