Convert struct to char * pointer in C
I have a structure:
struct K
{
char a[10];
char b[10];
};
I want to convert this structure to a char * pointer and print the value to Uart. Uart takes a char * pointer as input.
My main function looks like this:
void main()
{
struct K x= { "Hello","Pollo"};
struct K *revert;
char *buffer;
buffer = (char *)&x;
revert = (struct K *) buffer;
printf("%s %s", revert->a,revert->b);
}
Note: printf () will not work, I am using UART.
I want to print the buffer value to the UART when done with struct pointer to pointer conversion char *
. Can this be done?
source to share
Another approach to splitting and recombining structural elements into a char * string is related to string functions sprintf
and then strncpy
. There are many, many ways to do this. Simple pointer arithmetic, etc. But this approach is pretty clean and simple:
#include <stdio.h>
#include <string.h>
struct K
{
char a[10];
char b[10];
};
int main (void)
{
char tmp[21] = {0};
char *buf = tmp;
struct K x = { "Hello","Pollo"};
struct K rev = {{0},{0}};
/* combine x.a & x.b into single string in buf */
sprintf (buf, "%s%s", x.a, x.b);
/* print the combined results */
printf ("\n combined strings: %s\n\n", buf);
/* get original lenght of x.a & x.b */
size_t alen = strlen(x.a);
size_t blen = strlen(x.b);
/* copy from buf into rev.a & rev.b as required */
strncpy (rev.a, buf, alen);
strncpy (rev.b, buf+alen, blen);
printf (" recombined: rev.a: %s rev.b: %s\n\n", rev.a, rev.b);
return 0;
}
Output
$ ./bin/struct2str
combined strings: HelloPollo
recombined: rev.a: Hello rev.b: Pollo
source to share
I would do the following:
void serialize(struct K x, char * dest)
{
memcpy(dest,x.a,10);
memcpy(&dest[10],x.b,10);
}
and
void deserialize(const char * src, struct K *x)
{
memcpy(x->a,src,10);
memcpy(x->b,&src[10],10);
}
Since there are ASCII strings inside your structure. If you had a different datatype I would probably use unsigned char *
as the type for the destination buffer for serialization.
source to share