Search code examples
cstructuartchar-pointer

Converting Structure to char* pointer in C


I am having a structure:

struct K 
{
  char a[10];
  char b[10];
};

I wish to convert this structure to a char* pointer and print the value on Uart. Uart takes char* pointer as input.

My main function looks like:

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() won't work, I am using a UART.

I want to print the buffer value on UART when it is done with converting structure pointer to char * pointer. Is it possible to do that?


Solution

  • Another approach to splitting and recombining the struct elements into a char* string is with the string functions sprintf and then strncpy. There are many, many ways to do this. Simple pointer arithmetic will do, etc.. But this approach is fairly clean and straightforward:

    #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