3

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.

3
  • 1
    You could use sprintf(a, "%p", b); to get the pointer into the buffer a. However, it could be that the buffer is not wide enough, depending on the size of the pointer. Actually, check out snprintf(), which should be safer. Commented Nov 15, 2014 at 8:56
  • what you miss is the fact that C strings are NULL terminated in fact b contains "abcdefghi\0". Commented Nov 15, 2014 at 9:03
  • you can: for(i = 0; a[i] = b[i]; i++); Commented Nov 15, 2014 at 12:18

3 Answers 3

5

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++)
Sign up to request clarification or add additional context in comments.

6 Comments

yes strings are NULL terminated in C, last char be '0'.
@philippelhardy Not '0', but '\0' or 0
yes i should not have used enclosing '. 0x0 the byte 0.
thanks This Answer is really help full butThere is One little Mistake just Like (i = 0; i <= 9; i++)
@Rio i < 10 is more clear than i <= 9 in C-based languages, so it's preferred.
|
1

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.

1 Comment

strlen() in each iteration is bad idea
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.