cancel
Showing results for 
Search instead for 
Did you mean: 

Could you please tell me to array to string?

Gz
Senior
Posted on May 17, 2018 at 04:07

Dear All;

   I would like to know when I have array and I would like to convert array to string.

char A[6] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };

char *B;

I would like to 

*B = 'ABCDEFG';

How should I do?

#c #hal
4 REPLIES 4
Bill Dempsey
Senior
Posted on May 17, 2018 at 04:32

Hi

When you have a string such as 'ABCDEFG' it actually takes 8 characters and is found in memory as:

'A'

'B'

'C'

'D'

'E'

'F'

'G'

'\0'

So you should get a compiler error in your code since you only declared 6 elements of the array but actually have 7 in the assignments.  But assuming you correct that, you still need to allocate an 8th character as '\0' as the string terminator.

Once that is corrected a pointer to char can be re-cast to point to an array of chars so you could say:

B = A;

As a homework assignment, what would happen if you did not declare the 8th character as '\0'?  Would you get an error with your statement B=A?  Answer back.

Regards

Bill
Gz
Senior
Posted on May 17, 2018 at 04:45

Dear Bill;

   Thank you for your answer. I would like to know how I convert array to string. I would like to compare string when I received UART message. 

I received 

char A[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };

and I would like to compare to function 'if'. How should I do?

Such as :

if(A[8] == '9600')

{

   foo();

}

else

{

   while(1);

}

Regards

Mr.G

Posted on May 17, 2018 at 05:53

char *B;

B = 'ABCDEFG';

For compare see strcmp(), strncmp() or memcmp()

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Gz
Senior
Posted on June 07, 2018 at 12:01

Thank you. I am done.